[英]LINQ to SQL: Check for existence of a generic entity in a generic Repository
I have a generic repository as like that 我有一个像这样的通用存储库
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);
}
....
}
Is it possible to add a generic method to this repository to check for the existence of any entity like that: 是否可以向该存储库添加通用方法以检查是否存在任何类似这样的实体 :
public bool IsExisted(T entity)
{
...
}
it is easy to write it in any repository 在任何存储库中编写它都很容易
_productRepository.GetBy(p => p.Id == 5 // or whatever);
where the productRepository like this: productRepository如下所示:
public class ProductRepository : Repository<Product>
{
public ProductRepository()
: base()
{
}
}
I came to this since i always want to check for the existence of an entity alot, so i don't need to write the same method in all repositories. 我之所以来到这里,是因为我总是想检查一个实体是否存在,所以我不需要在所有存储库中都编写相同的方法。
If all your entities have for example a property Guid Id you can create the following interface for your entities: 例如,如果您所有的实体都具有属性Guid Id,则可以为您的实体创建以下接口:
public interface IEntity
{
Guid Id { get; set; }
}
And restrict your Repository class to it: 并限制您的存储库类:
public class Repository<T> : IRepository<T>
where T : class, IEntity
{
....
}
You can then define the following function in your base repository: 然后,您可以在基本存储库中定义以下功能:
public bool Exists(T entity)
{
return GetTable.Any(e => e.Id == entity.Id);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.