In the Entity Framework, do the SingleOrDefault () and FirstOrDefault () methods have different behaviors?

9

What are the differences between SingleOrDefault() and FirstOrDefault() , and when to use it?

    
asked by anonymous 09.06.2014 / 00:18

1 answer

10

SingleOrDefault returns the only element in a string, or a default value if the string is empty; this method raises an exception if there is more than one element in the sequence. ( MSDN, Enumerable.SingleOrDefault Method (IEnumerable), 2014. Available at: link . Access date 08.Jun.2014 ). That is, if the query has only one record it can be used without problems, but more than one record it returns an exception equal to the image just below:

Itcanbeusedforprimarykeyfields(PrimaryKey)withoutproblems,andifithasnorecord,themethodreturnsthedefaultvalueofthetypeinformed.

FirstOrDefault > returns the first element of a string, or a default value if the string does not contain elements (MSDN, Enumerable Method.FirstOrDefault (IEnumerable), 2014. Available in: link . Access date: 08.Jun.2014). You do not have the same problem as SingleOrDefault , it searches the first element in several found, not emitting errors.

There is also the difference between these two methods in their generation of SQL : SingleOrDefault makes a Select Top(2) , whereas FirstOrDefault makes a Select Top(1) .

Conclusion:

If you want to only bring a record or test the occurrence of more items with an exception use SingleOrDefault , if you do not use FirstOrDefault , to bring the first occurrence or the default value.

References:

09.06.2014 / 00:18