了解如何使存储库查询异步
Understanding how to make repository queries asynchronous
我的存储库中有以下 LINQ 查询,其行为符合预期:
public ICollection<Address> GetManufacterAddressesFromProductId(Guid productId)
{
return Context.Products
.First(product => product.Id == productId)
.Manufacturer
.Addresses;
}
如何使此调用异步?这是我目前的解决方案,似乎...太长了?
public async Task<ICollection<Address>> GetManufacterAddressesFromProductIdAsync(Guid productId)
{
var product = await Context.Products.FirstAsync(x => x.Id == productId);
var manufacturerId = product.ManufacturerId;
return await Context.ManufacturerAddresses.Where(x => x.ManufacturerId == manufacturerId ).ToListAsync();
}
让我觉得这并没有真正正确地做事,因为无论如何它都必须等待第一个调用完成 - 有点违背要点?
通过以下方式:
public Task<ICollection<Address>> GetManufacterAddressesFromProductId(Guid productId)
{
return Context.Products
.Where(product => product.Id == productId)
.Select(product => product.Manufacturer.Addresses)
.FirstAsync();
}
另请注意同步版本无效。应该是:
public ICollection<Address> GetManufacterAddressesFromProductId(Guid productId)
{
return Context.Products
.Where(product => product.Id == productId)
.Select(product => product.Manufacturer.Addresses)
.First();
}
我的存储库中有以下 LINQ 查询,其行为符合预期:
public ICollection<Address> GetManufacterAddressesFromProductId(Guid productId)
{
return Context.Products
.First(product => product.Id == productId)
.Manufacturer
.Addresses;
}
如何使此调用异步?这是我目前的解决方案,似乎...太长了?
public async Task<ICollection<Address>> GetManufacterAddressesFromProductIdAsync(Guid productId)
{
var product = await Context.Products.FirstAsync(x => x.Id == productId);
var manufacturerId = product.ManufacturerId;
return await Context.ManufacturerAddresses.Where(x => x.ManufacturerId == manufacturerId ).ToListAsync();
}
让我觉得这并没有真正正确地做事,因为无论如何它都必须等待第一个调用完成 - 有点违背要点?
通过以下方式:
public Task<ICollection<Address>> GetManufacterAddressesFromProductId(Guid productId)
{
return Context.Products
.Where(product => product.Id == productId)
.Select(product => product.Manufacturer.Addresses)
.FirstAsync();
}
另请注意同步版本无效。应该是:
public ICollection<Address> GetManufacterAddressesFromProductId(Guid productId)
{
return Context.Products
.Where(product => product.Id == productId)
.Select(product => product.Manufacturer.Addresses)
.First();
}