Reputation:
I have a LINQ query and in some cases it returns no values. So I am using the Any()
to check for that so I can handle the code accordingly. But when I use Any()
or Count()
I get the following error:
{"Value cannot be null.\r\nParameter name: g"}
This is the code I am using:
var cQuery = (from a in gServiceContext.CreateQuery("contact")
where ((((EntityReference)a["accountid"]).Id.Equals(new Guid(p.AccountGuid))) &&
((a["firstname"].Equals(p.FirstName) && a["lastname"].Equals(p.LastName) && a["address1_stateorprovince"].Equals(p.State)) || (a["emailaddress1"].Equals(p.Email))))
select new
{
ContactId = !a.Contains("contactid") ? string.Empty : a["contactid"],
FirstName = !a.Contains("firstname") ? string.Empty : a["firstname"],
LastName = !a.Contains("lastname") ? string.Empty : a["lastname"],
State = !a.Contains("address1_stateorprovince") ? string.Empty : a["address1_stateorprovince"],
Email = !a.Contains("emailaddress1") ? string.Empty : a["emailaddress1"]
}).DefaultIfEmpty();
if (cQuery.ToList().Any())
{
// Do something if I get results
} else {
// Something else if no results
}
Any ideas what I am doing wrong? Seems like it should work for me. In the case that it is error out. It would be returning no results so I would want it to skip over the whats in the if
. But in other cases there will be results. Thanks!
UPDATE:
I know the code is ugly. Sorry.
It looks like the problem is the:
where ((((EntityReference)a["accountid"]).Id.Equals(new Guid(p.AccountGuid)))
It looks like the where is getting a NULL. How would I go about handling that so the error doesn't pop up?
Upvotes: 2
Views: 1444
Reputation: 6848
The parameter name "g" is the name of the parameter in the new Guid(string g)
constructor.
Therefore, I suspect your root cause is actually that P.AccountGuid
is null in certain circumstances.
Upvotes: 6
Reputation: 39
Why not just go for the ToList function instead?
var cQuery = (from a in gServiceContext.CreateQuery("contact")
where ((((EntityReference)a["accountid"]).Id.Equals(new Guid(p.AccountGuid))) &&
((a["firstname"].Equals(p.FirstName) && a["lastname"].Equals(p.LastName) && a["address1_stateorprovince"].Equals(p.State))
|| (a["emailaddress1"].Equals(p.Email))))
select new
{
ContactId = !a.Contains("contactid") ? string.Empty : a["contactid"],
FirstName = !a.Contains("firstname") ? string.Empty : a["firstname"],
LastName = !a.Contains("lastname") ? string.Empty : a["lastname"],
State = !a.Contains("address1_stateorprovince") ? string.Empty : a["address1_stateorprovince"],
Email = !a.Contains("emailaddress1") ? string.Empty : a["emailaddress1"]
}).ToList();
if (cQuery.Count > 0)
{
// Do something if I get results
}
else
{
// Something else if no results
}
Upvotes: 0