I've only just started delving into LINQ to CRM.
I've built the following query that gives me a bunch of data about each contact and their company from the 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
}
);
I then use a simple foreach to loop through each record and write it out:
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/>");
}
However, I get an 'object reference not set to an instance of an object' error when I run the page. The error gives the following info which currently means nothing to me:
[NullReferenceException: Object reference not set to an instance of an object.]
lambda_method(Closure , <>f__AnonymousTypef`2 ) +658
From a process of elimination I know that the issues lies with trying to write out the 'a.Organisation' which relates to 'c.ParentCustomerId.Name'.
Usinq LinqPad I can see that this LINQ brings up the ParentCustomerId and shows it having four children, namely:
So I know that I want 'c.ParentCustomerId.Name', however I'm not sure why I'm having this issue. It's possible but unlikely that some records (entities?) don't have a value for this.
Is there something I'm not doing right in terms of grabbing this data or is it simply that I'm not populating it with some sort of default data for when a record is empty/null ?
You just need to add some guards when you're using Contains or accessing child properties on something that may or may not be 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",
// ...