该代码会从继承的EF构造函数中运行吗?
假设我们有两个从 EF DbContext 继承的 DbContext:
using System.Data.Entity;
using System.Collections.Generic;
namespace myproject.Models
{
public class MyContext : DbContext
{
public MyContext(string nameOrConnectionString) : base(nameOrConnectionString)
{
Database.CommandTimeout = Config.DatabaseCommandTimeout;
Database.SetInitializer<MyContext>(null);
}
public MyContext() : this("name=MyDbContextConnectionString") { }
}
public class MyContext2ReadOnly : MyContext
{
public MyContext2ReadOnly() : base("MyDbContextConnectionStringReadOnly")
{
}
}
}
现在假设我们创建一个 MyContext2ReadOnly()
实例。 我的问题是 - 以下行会 Database.SetInitializer
是有效的,还是我必须在 MyContext2ReadOnly()
构造函数中再次调用它(?):
public class MyContext2ReadOnly : MyContext
{
public MyContext2ReadOnly() : base("MyDbContextConnectionStringReadOnly")
{
Database.SetInitializer<MyContext2ReadOnly>(null);
}
}
Imagine we have two DbContexts that inherit from EF DbContext as such:
using System.Data.Entity;
using System.Collections.Generic;
namespace myproject.Models
{
public class MyContext : DbContext
{
public MyContext(string nameOrConnectionString) : base(nameOrConnectionString)
{
Database.CommandTimeout = Config.DatabaseCommandTimeout;
Database.SetInitializer<MyContext>(null);
}
public MyContext() : this("name=MyDbContextConnectionString") { }
}
public class MyContext2ReadOnly : MyContext
{
public MyContext2ReadOnly() : base("MyDbContextConnectionStringReadOnly")
{
}
}
}
Now imagine we create an instance of MyContext2ReadOnly()
.
My question is - will the following line Database.SetInitializer<MyContext>(null);
from the parent constructor be valid, or do I have to call it again in the MyContext2ReadOnly()
constructor as such(?):
public class MyContext2ReadOnly : MyContext
{
public MyContext2ReadOnly() : base("MyDbContextConnectionStringReadOnly")
{
Database.SetInitializer<MyContext2ReadOnly>(null);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为 DbContext 在处理继承和构造函数时并不特殊。所以就做个测试吧。我将定义一个
Db
来替换DbContext
。它证明了
MyContext
构造函数中的所有内容都被调用了。I think
DbContext
is not special when handling inheritance and constructor. So just have a test. I will define aDb
to replaceDbContext
.It proves everything in
MyContext
constructor are called.