EF:带有 Context.Set<X> 的通用存储库导致“实体类型 X 不是当前上下文模型的一部分”

问题描述

我想创建一个如下所示的通用存储库:Generic Repository Pattern in C#
在展示细节之前,我先描述一下问题:
如果我在 DbSet<X> 类型的 DbContext 中创建一个显式成员,那么一切正常。但是当使用 DbContext 创建通用存储库并使用 Context.Set<X> 时,我在调用 The entity type X is not part of the model for the current context 时收到错误消息 Table.ToList()。我读过像 this 这样的线程,但 @danludwig 的解决方案不是通用的。我该如何解决这个问题?
详情如下:
模型如下:

[Table("MYSCHEMA.SOURCE")]
public class Source : Entity<string>
{
    private Source() : base("0") { }
    
    public Source(string id) : base(id)
    {   }

    [Column("ID")]
    public string Id {
        get { return base.Id; }
        set
        {
            base.Id = value;
        }
    }
    [Column("DESCRIPTION")]
    public string Description { get; set; }
}

这是第一个选项,其中包含模型的显式成员,该选项工作正常: DbContext 包含类 DbSetSource

public partial class SourceContext : DbContext
{
    public SourceContext()
        : base("name=MainConnectionString")
    {
    }

    public virtual DbSet<DomainLayer.Lookups.Source> Source { get; set; }
}

由非通用存储库调用:

class SourceRepository 
{
    private Context.SourceContext SourceContext { get; }
    public SourceRepository(Context.SourceContext sourceContext)
    {
        SourceContext = sourceContext;
    }

    public List<DomainLayer.Lookups.Source> GetSources()
    {
        return SourceContext.Source.ToList();
    }
}

这是导致错误的通用选项:
首先是上下文:

class LookupContext : DbContext
{
    public LookupContext()
        : base("name=MainConnectionString")
    {
    }
}

这里是使用 DbContext.Set 方法导致 error 的通用存储库:

class GenericLookupRepository<T> where T : class
{
    public Context.LookupContext LookupContext { get; set; } = new LookupContext();

    public GenericLookupRepository()
    {
    }

    public IList<T> GetAll()
    {
        DbSet<Source> Table = LookupContext.Set<Source>();
        return Table.ToList();  //!!!!! here we have the error
    }
}

通用存储库旨在加载查找表,如来源、输入法、地区、国家...。我创建了一个通用存储库,而不是为每个实体创建存储库。
在这个 thread 中,@ChrisPratt 说对于每个实体,我必须在 DbSet 中添加一个 DbContext。我的情况是这样吗?为什么有必要这样做,因为泛型类型 T 表示我要加载的表。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...