FindAsync和Include LINQ语句

我到目前为止的代码工作得很好

public async Task 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 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); } 

所以我面临这个错误

严重级代码描述项目文件行抑制状态错误CS1061’IQueryable’不包含’FindAsync’的定义,并且没有扩展方法’FindAsync’可以找到接受类型’IQueryable’的第一个参数(你是否缺少using指令或assembly参考?)

有任何线索如何修复它?

最简单的方法是使用FirstOrDefaultAsyncSingleOrDefaultAsync

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

您收到错误的原因是因为为DbSet定义了Find / FindAsync方法,但Include的结果是IQueryable

另一种方法是将FindAsync与显式加载相结合:

 model.Item = await db.Items.FindAsync(id); if (model.Item == null) { return HttpNotFound(); } await db.Entry(model.Item).Collection(i => i.ItemVerifications).LoadAsync(); 

如果您使用的是通用存储库,并且在运行时不了解PK,则此方法可以提供帮助:

 public interface IGenericRepository where TEntity : class { Task Get(int id, string[] paths = null); } public class GenericRepository : IGenericRepository where TEntity : class { private readonly ApplicationDbContext _context; private readonly DbSet _dbSet; public GenericRepository(ApplicationDbContext context) { _context = context; _dbSet = _context.Set(); } public async Task Get(int id, string[] paths = null) { var model = _dbSet.FindAsync(id); foreach (var path in paths) { _context.Entry(model.Result).Reference(path).Load(); } return await model; } }