![](/img/trans.png)
[英]Make IEnumerable Entity Framework result async Web API
[英]Entity Framework Core IEnumerable async
我已经在我的项目中实现了一个存储库模式并且有一个CoinRepository
并且我想添加一个新方法 ( GetValues
),它根据具有多个列的 Coin 表中的条件仅检索一列(值)。
这是CoinRepositopry
class 和方法。
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
方法吗?
Does the GetAllAsync
method execute a query in the database and retrieve all the records, then apply the conditions in code - or does it execute the query in the database like this 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
列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.