- 首先创建一个种子数据类 SeedData,并在其中添加你所需的数据:
public static class SeedData
{
public static void Seed(this ModelBuilder modelBuilder)
{
modelBuilder.Entity().HasData(
new Author { Id = 1, Name = "Jane Austen" },
new Author { Id = 2, Name = "Charles Dickens" },
new Author { Id = 3, Name = "Miguel de Cervantes" }
);
modelBuilder.Entity().HasData(
new Book { Id = 1, Title = "Pride and Prejudice", AuthorId = 1 },
new Book { Id = 2, Title = "Sense and Sensibility", AuthorId = 1 },
new Book { Id = 3, Title = "David Copperfield", AuthorId = 2 },
new Book { Id = 4, Title = "Don Quixote", AuthorId = 3 }
);
}
}
- 在配置DbContext时,在OnModelCreating方法中调用Seed方法:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity().ToTable("Author");
modelBuilder.Entity().ToTable("Book");
modelBuilder.Seed();
}
- 最后在运行应用程序之前使种子数据生效,可在Startup.cs文件中使用如下方法:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ApplicationDbContext context)
{
context.Database.Migrate();
app.UseMvc();
}