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

本文关键字:是否 存在 实体 存储 检查 to LINQ SQL | 更新日期: 2023-09-27 18:12:07

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

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);

其中productrerepository如下所示:

public class ProductRepository : Repository<Product>
{
    public ProductRepository()
        : base()
    {
    }
}

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

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

如果你所有的实体都有一个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);
}