EF:Migrations.Configuration与DropCreateDatabaseAlways的种子的种子? [英] EF: Seed of Migrations.Configuration vs Seed of DropCreateDatabaseAlways?
问题描述
我的问题原来是: DropCreateDatabaseIfModelChanges无法更新数据库?
但是我改变了它,因为这两种方法的作用更加模糊对于我
。
But I changed it because the role of these two methods is more ambiguous for me .
...................
...................
到目前为止,我知道使用 DropCreateDatabaseIfModelChanges
将在架构更改(IfModelChanges)时重新创建数据库。这意味着我不必担心迁移,因为它将从头重新创建数据库,对吧?
我首先创建了一个类 DataInitializer
继承自 DropCreateDatabaseIfModelChanges
,并实现了种子
方法与初始数据,并从 Database.SetInitializer(新的DataInitializer());
> Main 方法,但我仍然收到有关模型更改的错误,我应该添加迁移(因为我从实体中删除了一个属性来测试数据初始化)。
这是初始化器类:
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));
}
}
这些是我的问题:如果迁移是启用,如果我在配置类中使用初始数据实现了Seed方法,那么将调用哪一个(并且我已经在Configuration类中已经使用了已经有数据的Seed方法)
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)
在我添加迁移后,它会抛出此错误(不管我是否调用SetInitializer):
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.
推荐答案
你必须告诉网络.config文件在Model改变时使用初始化器类。在web.config文件中的entityFramework标签中添加以下代码。希望它会工作。
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>
这篇关于EF:Migrations.Configuration与DropCreateDatabaseAlways的种子的种子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!