gpt4 book ai didi

c# - 在通用存储库模式中使用可用的方法语法

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

所以我们使用 C# 和通用存储库来做一些事情,比如从数据库中检索记录。所以我们的实现类中有这样的东西。

    public async Task<IList<TEntity>> GetAllAsync(Expression<Func<TEntity, bool>> predicate)
{
IQueryable<TEntity> query = (predicate != null) ? context.Set<TEntity>().Where(predicate) : context.Set<TEntity>();
return await query.ToListAsync();
}

这里我们使用 where 子句来做一些过滤。我们面临的困难是如何利用我们可用的 LINQ 扩展方法。现在我们有了一个通过工作单元使用通用存储库类的服务。为简单起见,我省略了工作单元。

    public async Task<List<Product>> GetStockTransactionsAsync(string warehouse, string product)
{
var stockTransation= await _unitOfWork.stockRepository.GetAllAsync(p => p.product == product && p.warehouse == warehouse);
return null;
}

假设我们现在只想使用 LINQ 方法语法,类似这样的东西可以在我们的服务类方法中使用。

    var stockTransation= (await _unitOfWork.stockRepository.GetAllAsync(p => p.product == product && p.warehouse == warehouse)).Take(5);

通过这样做,我们已经毁掉了我真正热衷于维护的 IQueryable 东西,因为数据库的大小很大;我们想运行 SQL,而不是在内存中做任何事情。

有没有一种很好的方法来传递 LINQ 方法语法,就像我们为 select 或 includes 做谓词一样。所以我们可以在通用存储库方法中使用 Take(n)、Max、Sum() 等。有谁知道一个好的方法吗?

最佳答案

看起来你把它复杂化了。
您可以简单地返回 IQueryable<TEntity>来自您的存储库:

public interface IGenericRepository
{
IQueryable<TEntity> Set<TEntity>();
}

public class EntityFrameworkRepository : IGenericRepository
{
// ...
public IQueryable<TEntity> Set<TEntity>()
{
return _context.Set<TEntity>();
}
}

// usage
IGenericRepository repository = ...;
var stockTransation = repository.Set<Product>()
.Where(p => p.product == product && p.warehouse == warehouse)
.Take(5)
.ToArray();

在这种情况下,SQL 查询将仅在.ToArray() 之后生成并执行。只取 5 个符合此条件的项目 - 不会进行内存中过滤。

如果您需要实现任何自定义方法,您可以以类似 LINQ 的方式将其作为扩展方法来实现:

public static class QueryableExtensions
{
// This one doesn't make much sense, actually
public static IQueryable<TEntity> GetAll(this IQueryable<TEntity> queryable, Expression<Func<TEntity, bool>> predicate)
{
return predicate == null
? queryable
: queryable.Where(predicate);
}
}

// usage
IGenericRepository repository = ...;
var stockTransation = repository.Set<Product>()
.GetAll(p => p.product == product && p.warehouse == warehouse)
.Take(5)
.ToArray();

我以同步方式实现它以使其更简单,但它可以很容易地转换为异步代码。

关于c# - 在通用存储库模式中使用可用的方法语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43206105/

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