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 doesn’t exist.
```cs
return this.DataContext.MemberDaos.SingleOrDefault(m => m.MemberID == id); Share:
Share on LinkedIn
Quick Share: Your custom post text has been copied to your clipboard! Click the button below to open LinkedIn's share dialog, then paste it.
💡 Tip: LinkedIn will open in a new tab. Use Ctrl+V (or Cmd+V on Mac) to paste your text.
Note: LinkedIn will show the article preview. You can add your custom text above it.