EntityReference导致运行时错误
本文关键字:运行时错误 EntityReference | 更新日期: 2023-09-27 18:11:20
我在过去48小时内才开始研究LINQ to CRM,需要一些帮助。
我建立了以下查询,它从CRM中为我提供了关于每个联系人及其公司的一堆数据:
var contacts =
(
from c in context.ContactSet
join m in context.py3_membershipSet on c.ContactId equals m.py3_Member.Id
where m.statuscode.Value == 1
orderby c.LastName
select new
{
FirstName = c.FirstName,
LastName = c.LastName,
BranchCode = c.py3_BranchArea,
Branch = (c.FormattedValues.Contains("py3_brancharea") ? c.FormattedValues["py3_brancharea"] : "N/a"),
JobTitle = c.JobTitle,
Organisation = c.ParentCustomerId.Name,
joinedAsCode = c.py3_SOLACEMemberJoinedAs,
JoinedAs = (c.FormattedValues.Contains("py3_solacememberjoinedas") ? c.FormattedValues["py3_solacememberjoinedas"] : "N/a"),
Expertise = c.py3_SOLACEMemberAreasofExpertise
}
);
然后使用一个简单的foreach循环遍历每条记录并将其写出来:
foreach (var a in contacts)
{
Response.Write("<span style='font-size:small'>Firstname: " + a.FirstName + " | LastName: " + a.LastName + " | Job Title: " + a.JobTitle + "| Org: " + a.Organisation + " | Branch: " + a.Branch + " | Expertise: " + a.Expertise + " | Membership Product: " + a.JoinedAs + "</span><br/>");
}
然而,当我运行页面时,我得到一个"对象引用未设置为对象的实例"错误。错误给出了以下信息,目前对我来说没有任何意义:
[NullReferenceException: Object reference not set to an instance of an object.]
lambda_method(Closure , <>f__AnonymousTypef`2 ) +658
从排除过程中我知道问题在于试图写出与'c.ParentCustomerId.Name'相关的'a. organisation '
使用LinqPad,我可以看到这个LINQ带来了ParentCustomerId,并显示它有四个子节点,即:
- Id
- LogicalName <
- 名称/gh>
- 扩展数据
我知道我想要'c.ParentCustomerId。名字,但我不知道为什么我有这个问题。这是可能的,但不太可能,一些记录(实体?)没有这个值。
是否有一些我没有做正确的抓取这个数据,或者只是我没有填充它与某种默认的数据,当一个记录是空的/null ?
你只需要添加一些警卫当你使用包含或访问可能为null或不为null的东西的子属性:
FirstName = c.FirstName,
LastName = c.LastName,
BranchCode = c.py3_BranchArea,
Branch = (c.FormattedValues != null &&
c.FormattedValues.Contains("py3_brancharea") ?
c.FormattedValues["py3_brancharea"] : "N/a",
JobTitle = c.JobTitle,
Organisation = c.ParentCustomerId != null ? c.ParentCustomerId.Name : "N/a",
// ...