我'试图以异步方式运行我的控制器操作运行。 如何使用异步任务?或如何在异步方式运行如何使用异步任务<IActionResult>?或如何以异步方式在我的Asp.Net核心网络API
// Db context
public class DeptContext : DbContext
{
public LagerContext(DbContextOptions<LagerContext> options)
: base(options)
{
Database.Migrate();
}
public DbSet<Department> Departments { get; set; }
public DbSet<Product> Products { get; set; }
}
//这是我的接口IDepRepository
Task<Department> GetDepartmentWithOrWithoutProducts(int deptId, bool includeProducts);
//我的仓储类DepRepository
public class DepRepository : IDepRepository
{
private DeptContext db;
public DepRepository(DeptContext context)
{
db = context;
}
// I'am geting Department name with products or Without products
public async Task<Department> GetDepartmentWithOrWithoutProducts(int deptId, bool includeProducts)
{
if(includeProductss)
{
return await db.Departments.Include(c => c.Products).Where(s => s.deptId == deptId).SingleAsync();
}
return await db.Departments.Where(s => s.deptId == deptId).SingleAsync();
}
}
所以我应该如何现在做我的控制器这样做的异步方式:我尝试如下,但我不知道这是否是正确的做这样的下面: 我没有得到任何错误,但我不知道如果这是正确的方式...
using System.Threading.Tasks;
using System.Net;
using Microsoft.Data.Entity;
using Microsoft.EntityFrameworkCore;
[Route("api/departments")]
public class DepartmentsController : Controller
{
private IDeptRepository _deptInfoRepository;
public DepartmentsController(IDeptRepository deptInfoRepository)
{
_deptInfoRepository = deptInfoRepository;
}
[HttpGet("{id}")]
public async Task<IActionResult> GetDepatment(int id, bool includeProducts = false)
{
var dept = _deptInfoRepository.GetDepartmentWithOrWithoutProducts(id, includeComputers);
if(dept == null)
{
return BadRequest();
}
if(includeProducts)
{
var depResult = new DepartmentDto() { deptId = dept.deptId, deptName = dept.deptName };
foreach(var department in dept.Products)
{
depResult.Products.Add(new ProductDto() { productId = department.productId, deptId = department.deptId, ProductName = department.ProductName });
}
return Ok(depResult);
}
var departmentWithoutProductResult = new DepartmentsWithoutProductsDto() { DeptId = dept.deptId, DeptName = dept.DeptName};
return Ok(departmentWithoutProductResult);
}
我该如何做到异步的方式我的控制器..我不知道在哪里把这些await和ToListAsync()。先谢谢你!
'ToListAsync'作为'IQueryable'扩展名而不是'IEnumerable'扩展名存在。 List不实现'IQueryable'。你有'GetDepartments'的异步版本吗?如果是这样,你可以等待那个电话。 –
@ R.Richards感谢您的回复。你的意思是,如果我在我的GetDepartments中有异步并等待,那就足够了? –
不是。你需要的是GetDepartments的异步版本。这里的答案暗示了这一点。 GetDepartmentsAsync会返回任何GetDepartments返回的任务<>。这是必需的,因为如果没有基于任务的函数,就不能有效地使用async/await。 [看到这个](https://stackoverflow.com/questions/14455293/how-and-when-to-use-async-and-await)。 –