【发布时间】:2017-07-01 20:26:33
【问题描述】:
我正在尝试以异步方式运行我的控制器操作。 如何使用异步任务?或者如何以异步方式运行
// 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);
//还有我的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();
}
}
那么我现在应该如何在我的控制器中以异步方式进行操作:我尝试如下但我不知道这样做是否正确: 我没有收到任何错误,但如果它是正确的方式我不会...
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 中有 async 和 await 就足够了吗?
-
并非如此。您需要的是 GetDepartments 的异步版本。这里的答案暗示了这一点。 GetDepartmentsAsync 将返回 GetDepartments 现在返回的任何内容的 Task。这是必需的,因为如果没有基于任务的功能,您将无法有效地使用 async/await。 See this.
-
@R.Richards 再次感谢您,现在我已经更新了类似的详细代码,请您检查我的完整代码吗?
标签: c# asp.net-core asp.net-core-webapi