为什么Seed方法不能在数据库创建时运行

时间:2017-09-20 12:29:27

标签: c# entity-framework

请参阅以下代码:

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签名上添加断点并且永远不会到达。为什么呢?

1 个答案:

答案 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);

            }
    }