In the Entity Framework, do the Singleordefault() and Firstordefault() methods exhibit different behaviors?

Asked

Viewed 936 times

9

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

1 answer

10


Singleordefault returns the single element of a sequence, or a default value if the sequence is empty; this method generates an exception if there is more than one element in the sequence. (MSDN, Enumerable Method.Singleordefault (Ienumerable), 2014. Available at: http://msdn.microsoft.com/pt-br/library/bb342451%28v=vs.110%29.aspx. Date accessed. 08.Jun.2014). That is, if the query has only one record can be used without problems, but more than one record it returns an exception equal to the image below:

inserir a descrição da imagem aqui

Can be used for primary key fields (Primary Key) no problems, and if there is no record, the method returns the default value of the type reported.

Firstordefault returns the first element of a sequence, or a default value if the sequence does not contain elements (MSDN, Enumerable Method.Firstordefault (Ienumerable), 2014. Available in: http://msdn.microsoft.com/pt-br/library/bb340482%28v=vs.110%29.aspx. Date accessed: 08.Jun.2014). Does not have the same problem of Singleordefault, it searches for the first element in several found, not emitting errors.

There is also the difference between these two methods in their generation of SQL: The Singleordefault makes a Select Top(2), while, the Firstordefault makes a Select Top(1).

Completion:

If you want to bring only one record or test the occurrence of more items with one exception use Singleordefault, if you don’t use Firstordefault, to bring the first occurrence or the default value (default).

References:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.