c# .net entity framework prefill database code example
Example 1: seeding in ef6
public class SchoolContext: DbContext
{
public SchoolContext(): base("SchoolDB")
{
Database.SetInitializer(new SchoolDBInitializer());
}
public DbSet<Student> Students { get; set; }
public DbSet<Standard> Standards { get; set; }
}
public class SchoolDBInitializer : DropCreateDatabaseAlways<SchoolDBContext>
{
protected override void Seed(SchoolDBContext context)
{
IList<Standard> defaultStandards = new List<Standard>();
defaultStandards.Add(new Standard() { StandardName = "Standard 1", Description = "First Standard" });
defaultStandards.Add(new Standard() { StandardName = "Standard 2", Description = "Second Standard" });
defaultStandards.Add(new Standard() { StandardName = "Standard 3", Description = "Third Standard" });
context.Standards.AddRange(defaultStandards);
base.Seed(context);
}
}
Example 2: database hasData method C#
// it goes into class ApplicationDbContext : DbContext
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Author>().HasData(
new Author
{
AuthorId = 1,
FirstName = "William",
LastName = "Shakespeare"
}
);
modelBuilder.Entity<Book>().HasData(
new Book { BookId = 1, AuthorId = 1, Title = "Hamlet" },
new Book { BookId = 2, AuthorId = 1, Title = "King Lear" },
new Book { BookId = 3, AuthorId = 1, Title = "Othello" }
);
/*further relational instructions may come here, like:
modelBuilder.Entity<Author>()
.HasMany<Book>(a => a.Books)
.WithOne(b => b.Author)
.HasForeignKey(b => b.AuthorId);
}