Single() / SingleOrDefault()
|
First () / FirstOrDefault()
|
Single() - There is exactly 1 result, an exception is thrown if no result is returned or more than one result.
SingleOrDefault() – Same as Single(), but it can handle the null value.
|
First() - There is at least one result, an exception is thrown if no result is returned.
FirstOrDefault() - Same as First(), but not thrown any exception or return null when there is no result.
|
Single() asserts that one and only one element exists in the sequence.
|
First() simply gives you the first one.
|
When to use
Use Single / SingleOrDefault() when you sure there is only one record present in database or you can say if you querying on database with help of primary key of table.
|
When to use
Developer may use First () / FirstOrDefault() anywhere, when they required single value from collection or database.
|
Single() or SingleOrDefault() will generate a regular TSQL like "SELECT ...".
|
The First() or FirstOrDefault() method will generate the TSQL statment like "SELECT TOP 1..."
|
In the case of Fist / FirstOrDefault, only one row is retrieved from the database so it performs slightly better than single / SingleOrDefault. such a small difference is hardly noticeable but when table contain large number of column and row, at this time performance is noticeable.
| |
Sunday, August 12, 2018
SingleOrDefault() Vs. FirstOrDefault() in LINQ Query
Subscribe to:
Post Comments (Atom)
javascript Filter/index off
var family = [{"name":"Jack", "age": 26}, {"name":"Jill", "age"...
-
A3+C3 VLOOKUP(G3,$A$3:$B$10,2) sum Product Quantity Count Result 1 Mobile 2 1 Mobile 3 Keyboard 3 2 Mobile 6 TV 1 3 ...
-
EF CORE CLI > dotnet ef database update MyFirstMigration. Scaffold-DbContext Command Use Scaffold-DbContext to create a model based ...
No comments:
Post a Comment