我正在尝试使用 EntityFramework、内存数据库和数据库播种器创建 WCF 应用程序。但我卡住了。我不知道为什么这对 C# 来说太麻烦了。在 Java 中,这将是一个 10 分钟的任务,这个东西会运行。无论如何,这是我的 DBContext
代码:
public class AppDBContext : DbContext
{
private static readonly DbContextOptions options = new DbContextOptionsBuilder<AppDBContext>().UseInMemoryDatabase("INMEMO-DB").Options;
public AppDBContext() : base(options)
{
}
public DbSet<Notification> Notifications { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Notification>().HasData(
new Notification
{
Id = 1
},
new Notification
{
Id = 2
},
new Notification
{
Id = 3
}
);
base.OnModelCreating(modelBuilder);
}
}
如您所见,我正在使用 OnModelCreating
方法将数据播种到我的数据库中。该方法被调用,但不会插入任何数据。我做错了什么?
我对这个 C# 东西快没耐心了..
最佳答案
HasData
方法仅将实体配置为具有种子数据。
要真正播种您需要调用的数据库
Database.EnsureCreated();
请注意,这仅适用于数据库尚不存在(如内存数据库)的情况,因为 EnsureCreated
不执行其他操作。
对于现有数据库,您需要创建和应用迁移。
供引用:Data Seeding
关于c# - EF Core 播种机制不插入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60037589/