gpt4 book ai didi

c# - FindAsync 和 Include LINQ 语句

转载 作者:IT王子 更新时间:2023-10-29 04:37:01 24 4
gpt4 key购买 nike

我目前得到的代码工作正常

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

所以我面临这个错误

Severity Code Description Project File Line Suppression StateError CS1061 'IQueryable' does not contain a definition for'FindAsync' and no extension method 'FindAsync' accepting a firstargument of type 'IQueryable' could be found (are you missing ausing directive or an assembly reference?)

知道如何解决吗?

最佳答案

最简单的是使用FirstOrDefaultAsyncSingleOrDefaultAsync相反:

model.Item = await db.Items.Include(i => i.ItemVerifications)
.FirstOrDefaultAsync(i => i.Id == id.Value);

您收到错误的原因是因为 Find/FindAsyncDbSet<T> 定义了方法,但是 Include 的结果是IQueryable<T> .

另一种方法是结合FindAsyncexplicit 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 和 Include LINQ 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40360512/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com