我被分配了一个新的项目,我决定给EF一个go.In,这个项目我所做的就是获取数据,没有持久性,我必须实现一些缓存,仅此而已。
阅读有关存储库模式的文章,我发现了大量的代码样本等等。me.They将一对一的实体实现到存储库似乎是错误的。
在我的项目中,我只需要阅读数据而不是保存等等.只是阅读,我有1000多个实体,我不能创建10S存储库,这似乎都是错误的。
我决定从一个简单的开始,我需要的是:
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。
我如何实现我的具体存储库?任何建议或简单的测试样本都可以。
非常感谢
发布于 2013-12-08 08:34:52
首先,最好将GetAll()和Find()方法更改为返回IQueryable<T>而不是IEnumerable<T>,以便使用Linq到实体实现对数据集的进一步查询。
在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时假设您首先使用代码)
https://stackoverflow.com/questions/20451341
复制相似问题