gpt4 book ai didi

c# - LINQ 到 SQL : Check for existence of a generic entity in a generic Repository

转载 作者:太空宇宙 更新时间:2023-11-03 19:27:02 25 4
gpt4 key购买 nike

我有一个类似的通用存储库

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,您可以为您的实体创建以下接口(interface):

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

关于c# - LINQ 到 SQL : Check for existence of a generic entity in a generic Repository,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7858279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com