我'試圖以異步方式運行我的控制器操作運行。 如何使用異步任務?或如何在異步方式運行如何使用異步任務<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)。 –