C# 数据库初始值设定项不';在继承DbContext时无法运行
我正在尝试创建一个通用的DbContext,我可以在我的所有项目上使用它,我希望它能够创建一些表并为它们种子。因此,我尝试使用DbInitializer,但它似乎只在创建父上下文时起作用。如果我创建了另一个继承自它的上下文,则父级永远不会被种子化/初始化 这是正确的模式吗C# 数据库初始值设定项不';在继承DbContext时无法运行,c#,entity-framework,inheritance,dbcontext,C#,Entity Framework,Inheritance,Dbcontext,我正在尝试创建一个通用的DbContext,我可以在我的所有项目上使用它,我希望它能够创建一些表并为它们种子。因此,我尝试使用DbInitializer,但它似乎只在创建父上下文时起作用。如果我创建了另一个继承自它的上下文,则父级永远不会被种子化/初始化 这是正确的模式吗 public class TestParentContext : DbContext { static TestParentContext() { Database.SetInitializer
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);
公共类TestParentContext:DbContext
{
静态TestParentContext()
{
SetInitializer(新的TestInitializer());
}
}
公共类TestChildContext:TestParentContext
{
静态TestChildContext()
{
//无初始值设定项
}
}
公共类TestInitializer:IDatabaseInitializer
{
public void InitializeDatabase(TestParentContext上下文)
{
//这仅在调用数据库时运行。在TestParentContext上使用时初始化
抛出新的NotImplementedException();
}
}
//这不会引发异常
使用(TestChildContext ctx=newtestchildcontext())
ctx.Database.Initialize(true);
//这将抛出异常(正如我所希望的那样)
使用(TestParentContext ctx=newtestparentcontext())
ctx.Database.Initialize(true);
在web.config
中找到实体框架组,并相应地更改/添加上下文
<entityFramework>
<contexts>
<context type="<libName>.<Context Name>, <Lib Name>">
<databaseInitializer type="<Lib Name>.<Context Config>, <Lib Name>" />
</context>
</contexts>
....
....
可能
是TestChildContext
,
是TestInitializer
您应该已经为TestParentContext
准备了一个,不要删除/更改它