You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Linq Where访问可空对象属性报非静态方法调用需目标错误如何解决

解决方案

方案1:提前判断devTab是否为空(最简单高效,适配现有代码结构)

你遇到的报错本质是EF需要把查询表达式转为SQL执行,本地变量devTab的空值判断不属于数据库可识别的操作,所以不需要强行把空值判断塞进where条件里,提前在内存中做判断即可:

DeviceTable devTab = (from t in _db.DeviceTables
                      where t.DeviceType == devtype && t.IDPlant == id
                      select t)
                      .FirstOrDefault();

// 先判断devTab是否为空,为空直接返回空列表
var DeviceTabColumnsNameAndDesc = new List<dynamic>();
if (devTab != null)
{
    DeviceTabColumnsNameAndDesc = (from t in _db.DeviceTabCols
                                   where t.IDDevTab == devTab.ID
                                       && t.MeasureFamily != "KEY"
                                       && t.MeasureFamily != "DATETIME"
                                   select new
                                   {
                                       colName = t.ColumnName,
                                       colDescr = t.ColumnDescr
                                   })
                                   .ToList();
}

方案2:用导航属性优化查询(符合EF使用规范,减少数据库请求次数)

如果你的DeviceTable实体已经配置了和DeviceTabCols的一对多导航属性(比如属性名设为RelatedDeviceTabCols),可以直接关联查询,代码更简洁:

var devTab = _db.DeviceTables
                .Include(t => t.RelatedDeviceTabCols)
                .FirstOrDefault(t => t.DeviceType == devtype && t.IDPlant == id);

// 用null条件运算符规避空引用,为空时直接返回空列表
var DeviceTabColumnsNameAndDesc = devTab?.RelatedDeviceTabCols
                                       .Where(t => t.MeasureFamily != "KEY" && t.MeasureFamily != "DATETIME")
                                       .Select(t => new { colName = t.ColumnName, colDescr = t.ColumnDescr })
                                       .ToList() 
                                   ?? new List<dynamic>();

内容的提问来源于stack exchange,提问作者The Newbie Toad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 04:36:03