- 首先,在
DbContext
中添加一个bool
类型的属性,用于指示种子数据是否已添加。在下例中,我们将其命名为_isSeeded
:
public class ApplicationDbContext : DbContext
{
private bool _isSeeded;
public ApplicationDbContext(DbContextOptions options)
: base(options)
{
}
// Add entities here
public DbSet Products { get; set; }
public DbSet Categories { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Map entities to tables
modelBuilder.Entity().ToTable("Products");
modelBuilder.Entity().ToTable("Categories");
// Add seed data here
if (!_isSeeded)
{
modelBuilder.Entity().HasData(
new Category { Id = 1, Name = "Electronics" },
new Category { Id = 2, Name = "Clothing" },
new Category { Id = 3, Name = "Books" }
);
modelBuilder.Entity().HasData(
new Product { Id = 1, Name = "Laptop", Price = 1000m, CategoryId = 1 },
new Product { Id = 2, Name = "Smartphone", Price = 800m, CategoryId = 1 },
new Product { Id = 3, Name = "T-shirt", Price = 10m, CategoryId = 2 },
new Product { Id = 4, Name = "Jeans", Price = 50m, CategoryId = 2 },
new Product { Id = 5, Name = "The Catcher in the Rye", Price = 5m, CategoryId = 3 }
);
_isSeeded = true;
}
}
}
- 接下来,在
Program.cs
文件中配置WebHost
,并添加以下代码,以在应用程序启动时应用迁移并添加种子数据:
public class Program
{
public static void Main(string[] args)
{
var host = CreateWebHostBuilder(args).Build();
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
var context = services.GetRequiredService();
context.Database.Migrate();
// Manually apply seed data if not already seeded
if (!context._isSeeded)
{
context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [Categories] ON");
context.Categories.AddRange(
new Category { Id = 1, Name = "Electronics" },
new Category { Id = 2, Name