到目前为止,我得到的代码工作正常
public async Task<ActionResult> Details(Guid? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ItemDetailModel model = new ItemDetailModel();
model.Item = await db.Items.FindAsync(id);
if (model.Item == null)
{
return HttpNotFound();
}
return View(model);
}
但是我想多包含1个表,并且不能使用
FindAsync
public async Task<ActionResult> Details(Guid? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ItemDetailModel model = new ItemDetailModel();
model.Item = await db.Items.Include(i=>i.ItemVerifications).FindAsync(id);
if (model.Item == null)
{
return HttpNotFound();
}
return View(model);
}
所以我面对这个错误
任何线索如何解决?
最佳答案
最简单的是改为使用FirstOrDefaultAsync
或SingleOrDefaultAsync
:
model.Item = await db.Items.Include(i => i.ItemVerifications)
.FirstOrDefaultAsync(i => i.Id == id.Value);
出现错误的原因是因为
Find
定义了FindAsync
/DbSet<T>
方法,但是Include
的结果是IQueryable<T>
。另一种方法是将
FindAsync
与explicit loading结合使用:model.Item = await db.Items.FindAsync(id);
if (model.Item == null)
{
return HttpNotFound();
}
await db.Entry(model.Item).Collection(i => i.ItemVerifications).LoadAsync();
关于c# - FindAsync和包括LINQ语句,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40360512/