c# - 实体框架核心 IEnumerable 异步
问题描述
我已经在我的项目中实现了一个存储库模式,CoinRepository
并且我想添加一个新方法(GetValues
这是CoinRepositopry
类和方法。
public class CoinRepository : Repository<Coin>, ICoinRepository
{
public CoinRepository(MyContext context) : base(context) { }
public IEnumerable<decimal> GetValuesAsync(int gameId, int gameTableId, string partnerCurrencyId)
{
return GetAllAsync().Result
.Where(c => c.GameId == gameId && c.CurrencyId == partnerCurrencyId)
.Select(c => c.Value);
}
}
该GetAllAsync
方法是IRepository
接口中的一个方法,它返回一个Task <IEnumerable<Entity>>
.
public async Task<IEnumerable<T>> GetAllAsync(Expression<Func<T, bool>> filter = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, string includeProperties = null)
{
IQueryable<T> query = dbSet;
if (filter != null)
query = query.Where(filter);
if (includeProperties != null)
foreach (var includeProperty in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
query = query.Include(includeProperty);
if (orderBy != null)
return await orderBy(query).ToListAsync();
return await query.ToListAsync();
}
我的问题是:
我应该制作
GetValuesAsync
一个async
方法吗?该
GetAllAsync
方法是在数据库中执行查询并检索所有记录,然后在代码中应用条件 - 还是像这样在数据库中执行查询SELECT c.value FROM COIN c WHERE <condition>
?如果我的代码有问题并且速度不够快,我该如何修改它并以最优化的方式重构它?
谢谢
解决方案
我应该制作
GetValuesAsync
一个async
方法吗?
当然是。异步在调用堆栈中一直向上传播。通过访问Result
您正在阻塞线程并破坏异步的目的。
该
GetAllAsync
方法是在数据库中执行查询,检索所有记录,然后在代码中应用条件还是像这样在数据库中执行查询SELECT c.value FROM COIN c WHERE
?
您尚未提供表达式,Where
因此它将从数据库中检索所有行并在内存中进行过滤。
如果我的代码有问题并且速度不够快,我该如何修改它并以最优化的方式重构它?
public class CoinRepository : Repository<Coin>, ICoinRepository
{
public CoinRepository(MyContext context) : base(context) { }
public async Task<IEnumerable<decimal>> GetValuesAsync(int gameId, int gameTableId, string partnerCurrencyId)
{
var coins = await GetAllAsync(c => c.GameId == gameId && c.CurrencyId == partnerCurrencyId,
includeProperties: nameof(Coin.Value));
return coins.Select(c => c.Value);
}
}
这样,您将一个表达式传递给该表达式,该表达式GetAllAsync
可用于生成 SQL where 子句,并仅指定Value
要检索的列。
推荐阅读
- mongodb - $addFields MongoDb 中的 $match
- yaml - 将数组下标值传递给 Jekyll 包含
- fabricjs - 克隆后 Fabric.js 缺少属性
- c - 给出不时我得到随机数。> 55
- google-sheets - 谷歌电子表格 sumif 添加,字符串比较条件
- python - .gif 在 python 中没有响应
- javascript - Javascript Uncaught TypeError:无法使用for循环读取未定义的属性'0'来搜索数组
- c# - 在 C# 中使用图标(vbCritical、vbInformation)拦截 VB 消息框
- python - Pandas str.split() 无法与正则表达式一起正常工作
- python - 如何在 Python 中创建动态正则表达式?