EF非静态方法需要目标
我对以下查询存在严重问题。
context.CharacteristicMeasures .FirstOrDefault(cm => cm.Charge == null && cm.Characteristic != null && cm.Characteristic.Id == c.Id && cm.Line != null && cm.Line.Id == newLine.Id && cm.ShiftIndex != null && cm.ShiftIndex.Id == actShiftIndex.Id && (newAreaItem == null || (cm.AreaItem != null && cm.AreaItem.Id == newAreaItem.Id)));
我得到一个TargetException: Non-static method requires a target
当newAreaItem为null时, TargetException: Non-static method requires a target
。 如果newAreaItem不为null,则会出现NotSupportedException: Unable to create a constant value of type 'PQS.Model.AreaItem'. Only primitive types or enumeration types are supported in this context.
NotSupportedException: Unable to create a constant value of type 'PQS.Model.AreaItem'. Only primitive types or enumeration types are supported in this context.
我已经检查过它们是否为null:c,newLine,actShiftIndex所有3个变量都不为空且可以访问Id。
我不明白……请帮忙。
如果你需要更多信息..不要犹豫,问…
UPDATE
我可以消除NotSupportedException
,但是当newAreaItemIsNull为true时我仍然得到了TargetException ..:/
bool newAreaItemIsNull = (newAreaItem == null); var mc = context.CharacteristicMeasures .FirstOrDefault(cm => cm.Charge == null && cm.Characteristic != null && cm.Characteristic.Id == c.Id && cm.Line != null && cm.Line.Id == newLine.Id && cm.ShiftIndex != null && cm.ShiftIndex.Id == actShiftIndex.Id && (newAreaItemIsNull || (cm.AreaItem != null && cm.AreaItem.Id == newAreaItem.Id)));
UPDATE
我终于做到了。 似乎查询解析无法解析我的newAreaItem(IsNull)
因为它不是以某种方式在数据库模型中! 我必须分开我的查询..
bool newAreaItemIsNull = (newAreaItem == null); MeasureCharacteristic mc; if (newAreaItemIsNull) mc = context.CharacteristicMeasures .FirstOrDefault(cm => cm.Charge == null && cm.Characteristic != null && cm.Characteristic.Id == c.Id && cm.Line != null && cm.Line.Id == newLine.Id && cm.ShiftIndex != null && cm.ShiftIndex.Id == actShiftIndex.Id); else mc = context.CharacteristicMeasures .FirstOrDefault(cm => cm.Charge == null && cm.Characteristic != null && cm.Characteristic.Id == c.Id && cm.Line != null && cm.Line.Id == newLine.Id && cm.ShiftIndex != null && cm.ShiftIndex.Id == actShiftIndex.Id && cm.AreaItem != null && cm.AreaItem.Id == newAreaItem.Id);
有人知道更好的解决方案吗?
尝试在查询之外移动newAreaItem == null
bool newAreaItemIsNull = (newAreaItem == null);
并在查询中用newAreaItemIsNull
替换newAreaItem == null
。
查询解析器只能与数据库中的对象一起操作,而newAreaItem不是其中之一。
当newAreaItem == null
为true时,我遇到了完全相同的问题。
问题来自LINQ中使用的项不能为空的事实。 因此,当newAreaItem == null
为true时,表示newAreaItem
为null,这会导致抛出错误。
在我看来,你可以做的就是在检查newAreaItem == null
,如果newAreaIteam
为null,则将newAreaIteam
设置为该类型的新空对象。 newAreaItemIsNull
条件仍然存在,因此
(cm.AreaItem != null && cm.AreaItem.Id == newAreaItem.Id)
如果newAreaItem
为null,则仍然不会在下面的代码中进行评估。
context.CharacteristicMeasures. FirstOrDefault(cm => cm.Charge == null && cm.Characteristic != null && cm.Characteristic.Id == c.Id && cm.Line != null && cm.Line.Id == newLine.Id && cm.ShiftIndex != null && cm.ShiftIndex.Id == actShiftIndex.Id && (newAreaItem == null || (cm.AreaItem != null && cm.AreaItem.Id == newAreaItem.Id)));