我有一个通用的存储库就像那样
public class Repository<T> : IRepository<T> where T: class
{
DataContext _db;
public Repository()
{
_db = new DataContext("connection string");
}
System.Data.Linq.Table<T> GetTable
{
get { return _db.GetTable<T>(); }
}
public T GetBy(Func<T, bool> exp)
{
return GetTable.SingleOrDefault(exp);
}
....
}
是否可以向此存储库添加通用方法以检查是否存在任何实体:
public bool IsExisted(T entity)
{
...
}
很容易在任何存储库中编写它
_productRepository.GetBy(p => p.Id == 5 // or whatever);
其中productRepository如下:
public class ProductRepository : Repository<Product>
{
public ProductRepository()
: base()
{
}
}
我来到这里,因为我总是想检查实体的存在,所以我不需要在所有存储库中编写相同的方法。
答案 0 :(得分:6)
如果您的所有实体都有例如属性Guid ID,您可以为您的实体创建以下界面:
public interface IEntity
{
Guid Id { get; set; }
}
并将您的Repository类限制为:
public class Repository<T> : IRepository<T>
where T : class, IEntity
{
....
}
然后,您可以在基本存储库中定义以下函数:
public bool Exists(T entity)
{
return GetTable.Any(e => e.Id == entity.Id);
}