I have a many-to-one relationship that users can edit via checkboxes. PK of Foo is ID, and fid contains the id from the checkbox.
I’m checking to see if an element exists with:
Foo ent;
try
{
ent = ctx.Foo.First(f => f.ID == fid);
}
catch (System.InvalidOperationException ioe)
{
ent = new Foo();
}
It seems to me that I should be able to do this without throwing an exception. What would be the best way to do this?
The
InvalidOperationExceptionyou get has the message:The behaviour of
Firstis that it throws this exception if the element is not found.You can use
FirstOrDefaultinstead ofFirstand check fornull. The null-coalescing operator (??) can be used to make this check.Note also that there is a similar pair of functions,
SingleandSingleOrDefaultthat throw an exception if more than one matching element is found. In your specific case, assuming that the identities should be unique, it might be more appropriate to useSingleOrDefault.