Regarding FirstOrDefault or SingleOrDefault
what kind of data FirstOrDefault or SingleOrDefault will return.
suppose my query retu开发者_如何学编程rn 3 record like
empid ename salary
----- ----- ------
1 joy 1500
2 rob 4500
3 jen 6500
so if we use FirstOrDefault or SingleOrDefault then what kind of resultset i will get. please explain with example. thanks
| 0 values | 1 value | > 1 value
FirstOrDefault | Default | First value | First value
SingleOrDefault | Default | First value | Exception
And to extend this table to the entire set:
| 0 values | 1 value | > 1 value
First | Exception | First value | First value
FirstOrDefault | Default | First value | First value
Single | Exception | First value | Exception
SingleOrDefault | Default | First value | Exception
Last | Exception | Last value | Last value
LastOrDefault | Default | Last value | Last value
And here's another version with some concrete values to make it clearer:
| [] | [1] | [1,2,3]
First | Exception | 1 | 1
FirstOrDefault | 0 | 1 | 1
Single | Exception | 1 | Exception
SingleOrDefault | 0 | 1 | Exception
Last | Exception | 1 | 3
LastOrDefault | 0 | 1 | 3
SingleOrDefault will return exception because it wait to get one record or no record and FirstOrDefault will return the first record (1 joy 1500)
you can use SingleOrDefault when your where contains a condition that will surly return on record in you case - where empid == 1
obviously you want only one DB record with the ID 1
FirstOrDefault will return you the first element and the default value (default value for value type and null for reference type) the element if no elements are present.
SingleOrDefault will return the the element if only one is present. Default if none are present and throws an exception if more than one elements are in your query.
In your case FirstOrDefault will return the first element. And SingleOrDefault will throw an exception.
精彩评论