简体   繁体   English

实体框架中的覆盖种子方法

[英]Override Seed method in Entity Framework

I have an object Class : 我有一个对象Class:

 public  class Post
  {
     public int Id { get; set; }
     public string Title { get; set; }
     public string Content { get; set; }
  }

and i implemented a class to override Seed method like this : 我实现了一个类来重写Seed方法,如下所示:

 public class MyCustomInitialize : DropCreateDatabaseIfModelChanges<Context>
{
    protected override void Seed(Context context)
    {
        context.Posts.Add(new Post() { Content = "This is a test", Id = 2, Title = "my subject" });
        context.Database.ExecuteSqlCommand("CREATE INDEX IX_title ON Blog (title)");
        base.Seed(context);
    }
}

and in Program.cs : 并在Program.cs中:

 Database.SetInitializer(new  MyCustomInitialize());

but when i run my program, the record which i want to add to my DataBase ( with Title "my subject"), it didn't insert to my DB and the Index didn't create too! 但是,当我运行程序时,要添加到数据库中的记录(标题为“我的主题”)没有插入数据库,索引也没有创建! what is the problem? 问题是什么?

您需要在DbContext上调用SaveChanges。

The SetInitializer call should be in your global.asax in the Application_Start() event. SetInitializer调用应位于Application_Start()事件中的global.asax中。

protected void Application_Start()
{
    System.Data.Entity.Database.SetInitializer(new MyCustomInitialize());
}

EDIT: As amarano says in their answer the database has not been updated with the new 'Post' because you haven't called SaveChanges... 编辑:正如amarano在他们的回答中所说,数据库尚未使用新的“ Post”进行更新,因为您尚未调用SaveChanges ...

Which makes me wonder how are you inspecting whether the index has been applied? 这使我想知道您如何检查索引是否已应用?

Also you should call 你也应该打电话

Context.Entry(TheTrackedEntityYouWantToUpdate).Reload();

To update the local (in memory entity) after your ExecuteSqlCommand call. 在ExecuteSqlCommand调用之后更新本地(在内存实体中)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM