在我的数据库中,我有“Place”和“Image”表。 "Image"有一个来自 Place 的外键,这意味着每个地方可以有多个图像。
我选择这样的地方:
var query = (from x in DB.Places
where x.CityId == CityId
select x).ToList();
当我想通过以下方式访问其图像时:query.Images.toList();
我收到此错误:
The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
我的选择查询应该如何才能得到一个位置,它的图像只是通过一个选择查询??
提前致谢
马。
最佳答案
您可以使用预先加载:
var query = (from x in DB.Places
where x.CityId == CityId
select x).Include(p => p.Images).ToList();
在那种情况下方法语法看起来更好
var query = DB.Places.Where(p => p.CityId == CityId).Include(p => p.Images).ToList();
另一种选择 - 在获得图像之前不要处理 DbContext。例如。如果您正在使用 using
语句,只需在 using
block 中删除它或获取图像。但它将使用第二个 数据库查询来加载图像。
进一步阅读:Eager Loading和 Lazy Loading
关于c# - Entity Framework - 一对多 - 从两个表中选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42090972/