[英]LINQ to SQL: Check for existence of a generic entity in a generic Repository
我有一个像这样的通用存储库
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()
{
}
}
我之所以来到这里,是因为我总是想检查一个实体是否存在,所以我不需要在所有存储库中都编写相同的方法。
例如,如果您所有的实体都具有属性Guid Id,则可以为您的实体创建以下接口:
public interface IEntity
{
Guid Id { get; set; }
}
并限制您的存储库类:
public class Repository<T> : IRepository<T>
where T : class, IEntity
{
....
}
然后,您可以在基本存储库中定义以下功能:
public bool Exists(T entity)
{
return GetTable.Any(e => e.Id == entity.Id);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.