LINQ: Sequence contains no elements. InvalidOperationException when calling Single

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);

Instead of Single, use SingleOrDefault, which will return null if the object doesn’t exist.

return this.DataContext.MemberDaos.SingleOrDefault(m => m.MemberID == id);
Share