可以组成DbContext而不是继承吗?

rex*_*ghk 6 c# asp.net asp.net-mvc entity-framework simple-injector

假设我正在为一所学校进行代码优先开发,我有一个SchoolDbContext.有关实体框架的大多数文档建议您派生DbContext:

public class SchoolDbContext : DbContext
{
    public IDbSet<Student> Students => Set<Student>();
}
Run Code Online (Sandbox Code Playgroud)

但我的观点是SchoolDbContext从来没有的特例DbContext,它是不是仅仅利用的DbContext所以在我看来,SchoolDbContext应该组成DbContext:

public class SchoolDbContext
{
    private readonly DbContext _dbContext;

    public SchoolDbContext(DbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public IDbSet<Student> Students => _dbContext.Set<Student>();
}
Run Code Online (Sandbox Code Playgroud)

在我的ASP.NET MVC应用程序的组合根目录中,我通过设置这样的依赖项来尝试这种组合方法(使用Simple Injector作为示例):

private static void RegisterDependencies(Container container)
{
     // Assume I have a connection string SchoolDbContext
     container.Register(() => new DbContext("SchoolDbContext"), Lifestyle.Scoped);
     container.Register<SchoolDbContext>(Lifestyle.Scoped);
}
Run Code Online (Sandbox Code Playgroud)

Web.config文件:

<connectionStrings>
    <add name="SchoolDbContext"
         providerName="System.Data.SqlClient"
         connectionString="Server=(localdb)\MSSQLLocalDB;Integrated Security=true"/>
</connectionStrings>
Run Code Online (Sandbox Code Playgroud)

当我尝试加载时失败Students:

实体类型Student不是当前上下文的模型的一部分.

当我将其更改回继承方法(即调用默认构造函数new SchoolDbContext())时,一切都很完美.

实体框架不支持我的构图方法吗?

Nko*_*osi 5

可以组成DbContext而不是继承吗?

简答:没有

引用官方文件的评论(强调我的)

DbContext通常与派生类型一起使用,该派生类型包含 DbSet<TEntity>模型的根实体的属性.创建派生类的实例时,这些集会自动初始化 ....

还有更多,但这个答案太多了.

DbContext类

实体框架不支持我的构图方法吗?

如果查看源代码,DbContext可以使用内部方法在类中搜索DbSets并初始化它们.

主要是这部分代码

/// <summary>
///     Initializes the internal context, discovers and initializes sets, and initializes from a model if one is provided.
/// </summary>
private void InitializeLazyInternalContext(IInternalConnection internalConnection, DbCompiledModel model = null)
{
    DbConfigurationManager.Instance.EnsureLoadedForContext(GetType());

    _internalContext = new LazyInternalContext(
            this, internalConnection, model
            , DbConfiguration.GetService<IDbModelCacheKeyFactory>()
            , DbConfiguration.GetService<AttributeProvider>());
    DiscoverAndInitializeSets();
}

/// <summary>
///     Discovers DbSets and initializes them.
/// </summary>
private void DiscoverAndInitializeSets()
{
    new DbSetDiscoveryService(this).InitializeSets();
}
Run Code Online (Sandbox Code Playgroud)

您尝试获取的任何模型都会抛出相同的错误,因为模型在初始化时不是上下文的一部分,只有当它是派生类的成员时才会发生.

Github上的DbContext源代码