02 December 2007

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

 

Hope this helps.

Jon

Filed under: , ,
 

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# Noticias externas said:

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

02 December 07 at 3:56 AM
# Jakob Lanstorp said:

Thanks John, just what I needed.

13 March 08 at 6:45 AM
# Nick said:

Awesome, worked perfectly... thx Jon

12 April 08 at 3:38 PM
# Scott Pio said:

Thanks for this fix. It helped.

11 May 08 at 5:31 PM
# Carlos said:

Brilliant tip - solved my problem.  Thanks!

04 December 08 at 6:29 PM
# Ann said:

Thanks! Solved my problem, too ;-)

13 January 09 at 12:11 PM
# Sequence contains no elements. InvalidOperationException when calling Single said:

Thanks for quick tip! Very helpful!

08 February 09 at 10:38 AM
# Tushar said:

That was a quick help. Appreciate it.

22 November 09 at 8:52 AM

Leave a Comment

Comment Policy: No HTML allowed. URIs and line breaks are converted automatically. Your e–mail address will not show up on any public page.

(required) 
(optional)
(required) 

  
Enter Code Here: Required
Page view tracker