My code:
public string LocName(string locID)
{
var name = (from a in idc.Locations
where a.ID.ToString() == locID
select a.Name).Single();
return name;
}
I need it to return the name of the Location that matches the ID as a string for a TextBlock. Instead it returns no elements, I have checked that the ID is correct so it should return at least one element.
I have also tried:
where a.ID == new Guid(locID)
as well as
.First()
.FirstOrDefault()
have tried returning the result as an element and databinding to that but still – no elements.
What is the error???
Must be a casing issue if the data is there, you should always use
ToUpper()as that is optimised for string equality checks.Also you should always use
FirstOrDefaultasSinglewill throw an exception if there are more than one matches andFirstwill throw an exception if there are no matches. Try:EDIT: I’ve also added
Trimon the inputted value to sanitise the spaces. I’ve also added a null check on thelocIDparameter as that would blow up if it was passed is as null. Lastly, I added a??(coalesce) on thereturnstatement just incase it is returning null and you’re performing other things on that string (such asTrimorToLowerCase) as that would result in an exception.