当我运行此代码时
public PartialViewResult GetHardware()
{
IQueryable<Hardware> hardware = db.Hardwares;
HardwareState hwState = new HardwareState();
IQueryable<IGrouping<string, Hardware>> groupByCategory = hardware.GroupBy(g => g.Category);
foreach (IGrouping<string, Hardware> group in groupByCategory)
{
hwState.GroupName = group.Key;
hwState.GroupUnitsCount = group.Count();
hwState.StorageReservedCount
= group.Where(m =>
m.Place.IsStorage == true &&
m.PlaceID != (int)Constants.HardwareState.Created &&
m.HardwareState == (int)Constants.HardwareState.Reserved).Count();
}
return PartialView(hwState);
}
我收到有关导航属性m.Place = null
当我使用foreach块的代码传输一些文本时
public PartialViewResult GetHardware()
{
IQueryable<Hardware> hardware = db.Hardwares;
HardwareState hwState = new HardwareState();
IQueryable<IGrouping<string, Hardware>> groupByCategory = hardware.GroupBy(g => g.Category);
hwState.StorageReservedCount
= hardware.Where(m =>
m.Place.IsStorage == true &&
m.PlaceID != (int)Constants.HardwareState.Created &&
m.HardwareState == (int)Constants.HardwareState.Reserved).Count();
foreach (IGrouping<string, Hardware> group in groupByCategory)
{
hwState.GroupName = group.Key;
hwState.GroupUnitsCount = group.Count();
}
return PartialView(hwState);
}
,导航属性未设置为空,并且未显示错误
.AsQueryable
或Include(x => x.Place)
等扩展方法无法帮助我
我该如何解决这个问题?
更新:如果我将类型更改为IEnumerable
而不是IQueryable
,它就会开始有效!
但我想使用IQueryable
类型
UPDATE2:对不起,当我写错误是一个空导航属性时,我没说错。实际上出现的错误 “已经有一个与此命令关联的打开DataReader,必须先关闭它。” 正如本answer所述,这是因为:(引用)
“这种情况总是发生的另一种情况是你迭代的时候 查询结果(IQueryable),您将触发延迟加载 在迭代中加载实体。“
但它没有说明如何在不使用ToList()或MARS
的情况下解决问题