我有简单的自主Web API应用程序。我安装了 EnityFramework6 软件包,并在< enityframework> 部分的 App.config 中添加了以下行:
<contexts>
<context type="simple_api.MyContext, simple_api">
<databaseInitializer type="simple_api.MyInitializer, simple_api" />
</context>
</contexts>
Initializer类如下:
public class MyInitializer : System.Data.Entity.DropCreateDatabaseIfModelChanges<Context>
{
protected override void Seed(Context context)
{
Console.log("My seed method");
var persons = new List<Person> { };
var john = new Person() { Firstname = "John", Lastname = "Doe" };
context.Persons.Add(john);
context.SaveChanges();
}
}
我启用并创建了迁移,但问题是运行它不会触发我的种子方法:
PM> Update-Database
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Applying explicit migrations: [201805210804206_initial].
Applying explicit migration: 201805210804206_initial.
Running Seed method.
我也尝试更改 App.config ,但似乎完全被忽略了,因为<context type="foobar, nomatterwhatishere">
不会触发任何警告也不会出错。
可能是什么问题?
-
顺便说一句,当我配置 log4net 时,文件也被忽略了,我必须调用log4net.Config.XmlConfigurator.Configure()
。也许EntityFramework有类似的东西?
答案 0 :(得分:0)
我错了:配置文件有效,但 DropCreateDatabaseIfModelChanges 的种子方法未被触发。我用 DropCreateDatabaseAlways 替换它,并在查询模型后抛出异常:
Failed to set database initializer of type 'simple_api.MyInitializer, simple_api' for DbContext type 'simple_api.MyContext, simple_api' specified in the application configuration. See inner exception for details.
经过一些调试后,我发现命名空间为simple_api
,但程序集名称为simple-api
,因此配置应如下所示:
...
<entityframework>
<contexts>
<context type="simple_api.MyContext, simple-api">
<databaseInitializer type="simple_api.MyInitializer, simple-api" />
</context>
</contexts>
...
</entityframework>
...
现在一切正常,但我不确定为什么是种子 没有调用 DropCreateDatabaseIfModelChanges 。