使用与异步包括等待 [英] Use of Include with async await

查看:142
本文介绍了使用与异步包括等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我返回一个'项目'通过它独特的标识符的EF查询。我使用MVC所提供的脚手架控制器和该工程确定,但现在我想它返回的属于该项目的标签列表。

I have an EF query in which I am returning an 'Item' by it's unique identifier. I'm using the scaffolded controller provided by MVC and this works ok, but now I want it to return a list of tags which belong to the item.

我想我可能可以使用包含如下图所示,以预先抓取标签。然而,这似乎并没有使用异步时被允许的。

I thought I might be able to use 'Include' as shown below to eager fetch the tags. However this does not seem to be allowed when using async.

Item item = await db.Items.Include("Tags").FindAsync(id);

任何人都可以解释为什么这不会工作,并提出另一种方法带回项目的标签?

Can anybody explain why this won't work and suggest an alternative way to bring back the item's tags?

干杯

推荐答案

查找() FindAsync()上键入 DbSet 方法(这是 db.Items 是)。 包括()返回的DBQuery 对象,这就是为什么 FindAsync()不可用。使用 SingleOrDefaultAsync()做同样的事情 FindAsync()(不同的是它会直接进入数据库并且不会看起来在上下文以查看是否该实体第一存在)...

Find() and FindAsync() are methods on type DbSet (which is what db.Items is). Include() returns a DbQuery object, which is why FindAsync() is not available. Use SingleOrDefaultAsync() to do the same thing as FindAsync() (the difference is it will go straight to the database and won't look in the context to see if the entity exists first)...

Item item = await db.Items.Include("Tags").SingleOrDefaultAsync(i => i.Id == id);

这篇关于使用与异步包括等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆