EF: Seed of Migrations.Configuration vs Seed of DropCreateDatabaseAlways?

泄露秘密 提交于 2019-12-11 04:47:18

问题


My Question was originally: DropCreateDatabaseIfModelChanges fails to update database?

But I changed it because the role of these two methods is more ambiguous for me .

...................

What I know so far that using DropCreateDatabaseIfModelChanges will recreate the database whenever the schema changes (IfModelChanges). That mean that I don't have to worry about migration, since it will recreate the database from scratch anyway, right? I first created a class DataInitializer inheriting from DropCreateDatabaseIfModelChanges, and implemented the Seed method with the initial data, and called the Database.SetInitializer(new DataInitializer()); from the Main method, but I still get the error about model changing and I should add a migration (since I dropped a property from the entity to test the data initializing). this is the initializer class:

public class DataInitializer : DropCreateDatabaseIfModelChanges<BlogContext>
    {
        protected override void Seed(BlogContext context)
        {
            var blogs = new List<Blog>
            {
                new Blog {FollowersCount=456, Name="ABC", Url="abc.com" },
                new Blog {FollowersCount=789, Name="DEF", Url="def.com" },
                new Blog {FollowersCount=246, Name="GHI", Url="ghi.com" },
                new Blog {FollowersCount=135, Name="JKL", Url="jkl.com" },
                new Blog {FollowersCount=258, Name="MNO", Url="mno.com" },
            };
            blogs.ForEach(x => context.Blogs.Add(x));
        }
    }

These are my questions: Does it work if migration is enabled, and what happens if I'm implementing the Seed method in the Configuration class with initial data- which one will be called (and I have a Seed method initialized with data already in the Configuration class)

After I added a migration, it throws this error (whether I called SetInitializer or not):

There is already an object named 'Blogs' in the database.


回答1:


You have to tell the web.config file to use your initializer class whenever Model changes. Add the following code in the entityFramework tag in web.config file. Hope it will work..

<contexts>
    <context type="YourProjectName.BlogContext,YourProjectName">
      <databaseInitializer type="YourProjectName.DataInitializer , YourProjectName" />
    </context>
</contexts> 


来源:https://stackoverflow.com/questions/39548257/ef-seed-of-migrations-configuration-vs-seed-of-dropcreatedatabasealways

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!