LINQ to SQL:检查通用存储库中是否存在通用实体

Mah*_*mal 1 c# generics domain-driven-design repository-pattern linq-to-sql

我有一个通用的存储库就像那样

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);
    }
    ....
}
Run Code Online (Sandbox Code Playgroud)

是否可以向此存储库添加通用方法以检查是否存在任何类似的实体:

public bool IsExisted(T entity)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

很容易在任何存储库中编写它

_productRepository.GetBy(p => p.Id == 5 // or whatever);
Run Code Online (Sandbox Code Playgroud)

其中productRepository如下:

public class ProductRepository : Repository<Product>
{
    public ProductRepository()
        : base()
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

我来到这里因为我总是想检查实体的存在,所以我不需要在所有存储库中编写相同的方法.

Wou*_*ort 6

如果您的所有实体都有例如属性Guid Id,您可以为您的实体创建以下界面:

public interface IEntity
{
    Guid Id { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

并将您的Repository类限制为:

public class Repository<T> : IRepository<T>
    where T : class, IEntity
{
   ....
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以在基本存储库中定义以下函数:

public bool Exists(T entity)
{
    return GetTable.Any(e => e.Id == entity.Id);
}
Run Code Online (Sandbox Code Playgroud)

  • 我让它在Linq to Entities的生产代码中运行,它运行得很好. (2认同)