请参阅以下代码:
public class MyReadContext
{
public MyReadContext()
: base()
//: base("DefaultConnection")
{
Database.SetInitializer<MyReadContext>(new DropCreateDatabaseIfModelChanges<MyReadContext>());
}
public DbSet<Product> products { get; set; }
public class MyReadInitializer : DropCreateDatabaseIfModelChanges<MyReadContext>
{
protected override void Seed(MyReadContext context)
{
context.products.Add(
new Product { description = "Product1" }
);
base.Seed(context);
}
}
}
最初由EF Code First创建数据库时不调用Seed方法,即我在Seed签名上添加断点并且永远不会到达。为什么呢?
答案 0 :(得分:0)
您需要致电await context.SaveChangesAsync()
或同步context.SaveChanges()
更改此行
Database.SetInitializer<MyReadContext>(new DropCreateDatabaseIfModelChanges<MyReadContext>());
到
Database.SetInitializer<MyReadContext>(new MyReadInitializer());
然后添加保存上下文
public class MyReadInitializer : DropCreateDatabaseIfModelChanges<MyReadContext>
{
protected override void Seed(MyReadContext context)
{
context.products.Add(
new Product { description = "Product1" }
);
context.SaveChanges()
base.Seed(context);
}
}