我对以下查询有严重的问题。
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)));
当 newAreaItem 为 null 时,我得到一个 TargetException: Non-static method requires a target
。
如果 newAreaItem 不为空,我将得到一个 NotSupportedException:无法创建类型为“PQS.Model.AreaItem”的常量值。在此上下文中仅支持原始类型或枚举类型。
我已经检查过它们是否为空的东西: c、newLine、actShiftIndex 3 个变量都不为空且 Id 可访问。
我不明白...请帮忙。
如果您需要更多信息..请随时询问...
更新
我可以消除 NotSupportedException
,但是当我的 newAreaItemIsNull 为真时我仍然得到 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)));
更新
我终于做到了。查询解析似乎无法解析我的 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);
并在查询中将 newAreaItem == null
替换为 newAreaItemIsNull
。
查询解析器只能对数据库中的对象进行操作,newAreaItem 不是其中之一。
关于c# - EF 非静态方法需要一个目标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15498981/