c# - 将接口(interface)与 DbSet 一起使用,是否可以与 EF Core 一起使用?

标签 c# entity-framework-6 ef-core-2.0

Back in EF 4这是不可能的。是否可以使用带有 DbSet 的接口(interface)?在 EF6 或 EF Core 中?

public class LfSp3Ctx : DbContext, ILfSp3Ctx
{
    public DbSet<ILfSp3Project> ProjectSE { get; set; }
}

最佳答案

这是可能的,但它需要一些技巧。 EF 只会直接实例化 DbSet 类型。因此,您必须创建自己的接口(interface)来包装/公开您想要的所有 DbSet 方法,并且实际实现在其构造函数中采用 DbSet 实例。然后在 DbContext 类上,您必须执行以下操作:

IDbSet<DigimonEntity> DigimonRepository => new DbSetRepository<DigimonEntity>(this.Digimons);

DbSet<DigimonEntity> Digimons { get; set; }

public class DbSetRepository<T> : IDbSet<T> where T : class
{
    private readonly DbSet<T> _set;
    public DbSetRepository(DbSet<T> set) => _set = set;

    public Type ElementType => ((IQueryable<T>)_set).ElementType;
    public Expression Expression => ((IQueryable<T>)_set).Expression;
    public IQueryProvider Provider => ((IQueryable<T>)_set).Provider;
    public IEnumerator<T> GetEnumerator() => ((IEnumerable<T>)_set).GetEnumerator();
    IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable<T>)_set).GetEnumerator();

    void IDataStoreRepositoryWrite<T>.Add(T entity) => _set.Add(entity);
    void IDataStoreRepositoryWrite<T>.Update(T entity) => _set.Update(entity);
    void IDataStoreRepositoryWrite<T>.Delete(T entity) => _set.Remove(entity);

    Task IDataStoreRepositoryWrite<T>.AddAsync(T entity, CancellationToken token) => _set.AddAsync(entity, token);
}

像这样的东西。我的有点特定于我当时试图实现的实现。 :)

关于c# - 将接口(interface)与 DbSet 一起使用,是否可以与 EF Core 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48061009/

相关文章:

c# - EntityCommandCompilationException 指定的方法不支持 Entity Framework

c# - Entity Framework 6 : related entities auto added to parent entity despite lazy loading being turned off

entity-framework - 无法使用 Entity Framework Core (.net core) 验证实体

linq - 属性 'a' 不是实体类型 'b' 的导航属性。为什么不?

c# - 将matlab函数集成到c#项目中

c# - 如何使用新的 Azure 存储 SDK v12 打开新 Blob 的可写流?

c# - 测试 Entity Framework 查找方法

c# - 如何将List <Object>转换为继承类的数组?

c# - 连接的当前状态是 connecting