如何使用异步 Task<IActionResult> ?或者如何在我的 Asp.Net Core Web Api 中以异步方式运行

Hel*_*kie 6 c# asp.net-core asp.net-core-webapi

我正在尝试以异步方式运行我的控制器操作。如何使用异步任务?或者如何以异步方式运行

// 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; }


}
Run Code Online (Sandbox Code Playgroud)

// 这是我的接口 IDepRepository

Task<Department> GetDepartmentWithOrWithoutProducts(int deptId, bool includeProducts);
Run Code Online (Sandbox Code Playgroud)

// 还有我的 Repository 类 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

那么我现在应该如何在我的 Controller 中以异步方式执行此操作:我尝试了以下操作,但我不知道这样做是否正确:我没有收到任何错误,但如果正确,我不会道路 ...

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);


    }
Run Code Online (Sandbox Code Playgroud)

我该怎么做才能以异步方式让我的控制器......我不知道把那些 await 和 ToListAsync() 放在哪里。先感谢您!

Nko*_*osi 9

应该重命名界面以更好地显示意图。

public interface IDepRepository {
    Task<Department> GetDepartmentWithOrWithoutProductsAsync(int deptId, bool includeProducts);
    //...
}
Run Code Online (Sandbox Code Playgroud)

这将相应地更新实现。由于该方法在异步调用后实际上并未使用任何内容,因此实际上没有任何理由将该方法标记为异步。只需返回任务即可。

public Task<Department> GetDepartmentWithOrWithoutProductsAsync(int deptId, bool includeProducts) {
    if(includeProductss) {
        return db.Departments.Include(c => c.Products).Where(s => s.deptId == deptId).SingleAsync();
    }
    return db.Departments.Where(s => s.deptId == deptId).SingleAsync();
}
Run Code Online (Sandbox Code Playgroud)

然而,控制器操作需要等待任务,然后在任务完成后继续,因此该方法将被标记为异步。

[HttpGet("{id}")]
public async Task<IActionResult> GetDepatment(int id, bool includeProducts = false) {
    var dept = await _deptInfoRepository.GetDepartmentWithOrWithoutProductsAsync(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);
}
Run Code Online (Sandbox Code Playgroud)