Jon Gallant

LINQ: Sequence contains no elements. InvalidOperationException when calling Single

1 min read

If you call Single to get an object from your DB and the object doesn’t exist you will get an InvalidOperationException.

return this.DataContext.MemberDaos.Single(m => m.MemberID == id);
```text
Instead of Single, use SingleOrDefault, which will return null if the object doesnt exist.
```cs
return this.DataContext.MemberDaos.SingleOrDefault(m => m.MemberID == id);
Share:
Share on X