Generic Repository EntityFramework 6 Implementation



我被分配了一个新项目,我决定试试EF。在这个项目中,我所做的只是获取数据——没有持久性。我必须实现一些缓存,仅此而已

在阅读关于存储库模式的文章时,我发现了大量的代码示例等……它们对我来说似乎都是错误的。它们实现了一对一的实体到存储库。

在我的项目中,我只需要阅读数据,而不是保存等等……只是阅读。我有100个实体,我无法创建100个存储库,这似乎都是错误的。

我决定从简单开始,我所需要的就是:

public interface IRepository : IDisposable
{
    IEnumerable<T> GetAll<T>() where T : class;
    IEnumerable<T> Find<T>(Expression<Func<T, bool>> predicate) where T : class;
    T GetOne<T>(Expression<Func<T, bool>> predicate) where T : class;
}
public class Repository : IRepository
{
    public IEnumerable<T> GetAll<T>() where T : class
    {
        return ???.ToArray();
    }
    public IEnumerable<T> Find<T>(Expression<Func<T, bool>> predicate) where T : class
    {
        return ???.Where(predicate).ToArray();
    }
    public T GetOne<T>(Expression<Func<T, bool>> predicate) where T : class
    {
        return ???.Where(predicate).FirstOrDefault();
    }
    public void Dispose()
    {
        throw new NotImplementedException();
    }
}

我正在挣扎的是我把"???"放在哪里,这应该是我的IdbSet。

我如何实现我的具体存储库?任何建议或没有测试样本都可以。

非常感谢

首先,您最好将GetAll()Find()方法更改为返回IQueryable<T>而不是IEnumerable<T>,以便使用Linq to Entities实现对数据集的进一步查询。

对于EF的实现,请尝试以下操作:

public class EFRepository : DbContext, IRepository
{
    // ctor:
    // pass a full connecting-string, or "name=someName" from configuration
    public EFRepository(string connectionStringOrName) : base(connectionStringOrName)
    {
          // init sets
          this.Entities1 = this.Set<EntityOfSomeType>();
          this.Entities2 = this.Set<EntityOfOtherType>();
    }
    public IEnumerable<T> GetAll<T>() where T : class
    {
        return this.Set<T>().ToArray();
    }
    public IEnumerable<T> Find<T>(Expression<Func<T, bool>> predicate) where T : class
    {
        return this.Set<T>().Where(predicate).ToArray();
    }
    public T GetOne<T>(Expression<Func<T, bool>> predicate) where T : class
    {
        return this.Set<T>.FirstOrDefault(predicate);
    }
    public void Dispose()
    {
        base.Dispose();
    }
    // Your DbSets...
    public IDbSet<EntityOfSomeType> Entities1 { get; set; }
    public IDbSet<EntityOfAnotherType> Entities2 { get; set; }
}

(我使用DbContext时假设您先编写代码)

最新更新