【发布时间】: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