Linq查询报错:未定义ClientRequest类型变量‘s’求修复方案
问题:LINQ查询CRM数据时抛出未定义变量异常
我编写了一个从CRM中按指定条件筛选客户请求列表的C#函数,代码如下:
public static List<ClientRequest> funcion(CrmContext crmContext, Guid year) { return (from s in crmContext.Xrm.allClientRequests where s.currentAccount != null && s.currentAccount.Id == s.lastAccount.Id && s.year.Id == year select s) .ToList(); }
运行时抛出异常:
"variable 's' of type 'ClientRequest' referenced from scope '', but it is not defined"
我推测问题出在条件语句s.currentAccount.Id == s.lastAccount.Id,认为编译器无法识别右侧的s,请问我的判断是否正确?该如何修复此问题?
解答
你的判断不完全准确,问题根源不是编译器识别不了右侧的s,而是LINQ to CRM的表达式解析器在处理导航属性间的ID比较时,加上缺少lastAccount的非空判断,导致表达式树解析出错,进而抛出变量作用域异常。
修复步骤:
- 补充非空判断:必须确保
s.lastAccount不为null,否则不仅会触发空引用异常,还会干扰表达式解析器对变量作用域的识别 - 修正函数名拼写(可选但推荐):
funcion是拼写错误,改为GetClientRequests这类语义明确的名称
修复后的代码:
public static List<ClientRequest> GetClientRequests(CrmContext crmContext, Guid year) { return (from s in crmContext.Xrm.allClientRequests where s.currentAccount != null && s.lastAccount != null // 新增lastAccount非空判断 && s.currentAccount.Id == s.lastAccount.Id && s.year.Id == year select s) .ToList(); }
替代方案(若上述修复仍无效):
如果LINQ查询表达式的解析仍有问题,可以改用方法链语法,部分场景下能绕过表达式解析器的限制:
public static List<ClientRequest> GetClientRequests(CrmContext crmContext, Guid year) { return crmContext.Xrm.allClientRequests .Where(s => s.currentAccount != null && s.lastAccount != null && s.currentAccount.Id == s.lastAccount.Id && s.year.Id == year) .ToList(); }
注意:如果数据量较大,避免先调用
ToList()再过滤,会导致全表加载影响性能。
内容的提问来源于stack exchange,提问作者miri
相关产品推荐
相关产品推荐

