【问题标题】:ASP.NET Web API - App.config does not work?ASP.NET Web API - App.config 不起作用?
【发布时间】:2018-05-21 09:14:55
【问题描述】:

我有一个简单的自托管 Web API 应用程序。我安装了 EnityFramework6 包并在 部分下的 App.config 中添加了以下行:

<contexts>
    <context type="simple_api.MyContext, simple_api">
        <databaseInitializer type="simple_api.MyInitializer, simple_api" />
    </context>
</contexts>

初始化器类如下:

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();
    }
}

我启用并创建了迁移,但问题是运行它不会触发我的 Seed 方法:

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,但似乎完全被忽略了,因为&lt;context type="foobar, nomatterwhatishere"&gt; 不会触发任何警告或错误。

可能是什么问题?

--

顺便说一句,当我配置 log4net 时,文件也被忽略了,我必须调用 log4net.Config.XmlConfigurator.Configure()。也许 EntityFramework 也有类似的东西?

【问题讨论】:

标签: asp.net entity-framework asp.net-web-api


【解决方案1】:

我错了:配置文件有效,但未触发 DropCreateDatabaseIfModelChangesSeed 方法。我将其替换为 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>
...

现在一切正常,但我不确定为什么 Seed DropCreateDatabaseIfModelChanges 没有调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-12
    • 2018-01-01
    • 2018-11-25
    • 2019-04-30
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多