【问题标题】:DatabaseInitializer doesn't run on when inheriting DbContext继承 DbContext 时 DatabaseInitializer 不运行
【发布时间】:2014-12-12 14:02:05
【问题描述】:

我正在尝试创建一个通用的 DbContext,我可以在我的所有项目中使用它,并且我希望它能够创建和播种一些表。所以我尝试使用 DbInitializer 但它似乎只在创建父上下文时才有效。如果我创建另一个继承自它的上下文,则父级永远不会被播种/初始化。

这甚至是正确的使用模式吗?

public class TestParentContext : DbContext
{
    static TestParentContext()
    {
        Database.SetInitializer<TestParentContext>(new TestInitializer());
    }
}

public class TestChildContext : TestParentContext
{
    static TestChildContext()
    {
        //no initializer
    }
}

public class TestInitializer : IDatabaseInitializer<TestParentContext>
{
    public void InitializeDatabase(TestParentContext context)
    {
        //this only gets run when calling Database.Initialize when used on a TestParentContext
        throw new NotImplementedException();
    }
}

//this will not throw the exception
using (TestChildContext ctx = new TestChildContext())
    ctx.Database.Initialize(true);

//this will throw the exception (as I want it to)
using (TestParentContext ctx = new TestParentContext())
    ctx.Database.Initialize(true);

【问题讨论】:

    标签: c# entity-framework inheritance dbcontext


    【解决方案1】:

    在您的 web.config 中找到实体框架组并相应地更改/添加上下文

    <entityFramework>
      <contexts>
        <context type="<libName>.<Context Name>, <Lib Name>">
          <databaseInitializer type="<Lib Name>.<Context Config>, <Lib Name>" />
        </context>
      </contexts>
    ....
    

    可能&lt;ContextName&gt;TestChildContext&lt;Context Config&gt;TestInitializer 你应该已经有一个TestParentContext 不要删除/更改它。

    【讨论】:

      猜你喜欢
      • 2020-10-13
      • 2011-07-15
      • 1970-01-01
      • 1970-01-01
      • 2020-11-13
      • 1970-01-01
      • 2016-07-19
      • 2019-10-22
      • 1970-01-01
      相关资源
      最近更新 更多