Are there any differences between First and Single? [duplicate]

0

Are there any differences between First and Single?

Are the two queries returned the same?

And what about performance between the two is the same?

Which of the two expressions is best to use?

    
asked by anonymous 12.11.2016 / 20:07

2 answers

5

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

First will not throw exception for this case, and will return TOP 1 of result. One or more records are expected, 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 one to use for each scenario.

    
12.11.2016 / 20:17
0

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

Most recommended and First , instead of Single , for three reasons;

  • When you know you are retrieving an object, there will be no point in issuing a TOP 2 against the database;
  • Single is slightly slower than First ; and
  • Checking only one record for the input parameters should be the responsibility of the update phase of the database, not the query.
  • 12.11.2016 / 20:18