问题
Why is this Task not returning anything to the view? If I convert it to synchronous then it works, or if I step through the async task in visual studio, it works also.
public async Task<ActionResult> Load()
{
var housing = _db.Housing.ToListAsync();
var school = _db.Schools.ToListAsync();
var projects = _db.Projects.ToListAsync();
await Task.WhenAll(housing, school, projects);
var vm = new ItemViewModel
{
HousingTotals = await housing,
SchoolTotals = await school,
ProjectTotals = await projects
};
return PartialView(vm);
}
回答1:
Entity Framework can not handle multiple concurrent requests using a single DbContext. You need to await each list before you move on to the next one or use 3 separate DbContexts.
Here is how to do it just awaiting each request individually.
public async Task<ActionResult> Load()
{
var housing = await _db.Housing.ToListAsync();
var school = await _db.Schools.ToListAsync();
var projects = await _db.Projects.ToListAsync();
var vm = new ItemViewModel
{
HousingTotals = housing,
SchoolTotals = school,
ProjectTotals = projects
};
return PartialView(vm);
}
With separate contexts.
private static YourContext GetContext()
{
return new YourContext();//Change as needed.
}
public async Task<ActionResult> Load()
{
using(var db1 = GetContext())
using(var db2 = GetContext())
using(var db3 = GetContext())
{
var housing = db1.Housing.ToListAsync();
var school = db2.Schools.ToListAsync();
var projects = db3.Projects.ToListAsync();
await Task.WhenAll(housing, school, projects);
var vm = new ItemViewModel
{
HousingTotals = await housing,
SchoolTotals = await school,
ProjectTotals = await projects
};
return PartialView(vm);
}
}
Note using the separate context method you are disposing of them so if you have navigation properties that are lazy loaded you use then those navigation properties will nolonger work. I would recommend using the first method of using a single context and awaiting each list so you keep the DbContext
alive for future requests using the lazy loaded navigation properties.
来源:https://stackoverflow.com/questions/30446100/async-controller-not-returning-anything-to-the-view-when-querying-multiple-datat