Is there a difference between First and Single?

Asked

Viewed 391 times

0

There are some differences between First and Single?

the return of the two consultations are equal?

And in the performance between the two is the same?

Which of the two expressions is best used?

  • 1

    @Virgilionovic, Singleordefault() and different from Single, although I didn’t find this question exactly because it was different. the same goes for First.

  • It’s not @Marconcilio Souza is the same thing! only has an extra increment that can return a default value! but, it’s the same thing! including part of Exception is identical!

  • @Virgilionovic, if it were the same thing, tell me why did you develop two methods with the same function? with different names? gave loka to the developers of Microsoft ?

  • @Virgilionovic, see this https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=6&cad=rja&uact=8&ved=0ahUKEwjlwtyFrajQAhURl5AKHeLND2IQFghHMAU&url=http%3A%2F%2Fwww.dotnettricks.com%2Flearn%2Flinq%2Funderstanding-single-singleordefault-fault-faultfirst-and-firstordefault&usg=Afqjcnfcrjuvhilyd9mzgwz7tjg54gz3za&bvm=bv.138493631,d.Y2I .....

  • They do the same thing, the only difference is that if there is no error they will return the value or a pattern. The link has not shown anything! Apologies ... !

  • Just remembering that duplicate more people evaluate not just me!

  • @Virgilionovic, doing the same thing and having a difference are separate things, I know that one single vote to close is not enough, but they followed in your footsteps after you signaled as duplicate.

Show 3 more comments

2 answers

5


Single will launch an exception if the query returns more than one record. Only one record is expected.

First will not throw exception to this case, and will return TOP 1 of the result. Expected 1 or more records, but returns only the first.

Both throw exception when no record is returned.

As you see, they are two different goals. It’s up to you to decide which to use for each scenario.

0

The subtle difference between First and Single is that the latter imposes the rule that the database query should return only one record. To ensure such restriction, the Single method issues a clause SQL TOP 2. If two records are returned, it gives an exception. If zero records are returned, it gives an exception, unless you use SingleOrDefault, who has the same behaviour as FirstOrDefault.

The most recommended and the First, instead of Single, for three reasons;

  1. When you know you are recovering an object, there is no point in sending a TOP 2 against the database;
  2. Single is slightly slower than First; and
  3. Checking only one record for input parameters should be the responsibility of the database update phase, not the query.

Browser other questions tagged

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