if you have a select LINQ query that should only return one result, do you have to have a foreach loop to get the result?
Or is there a better way?
// Will return a default value if no object is found in the DB
db.Table.SingleOrDefault(x => x.something == someParameter);
or
// Will throw an exception if records are not found
db.Table.Single(x => x.something == someParameter);
Thanks to Mehrdad for the comment...both lines have been updated.
If it's possible that your query could result in more than one record being returned, then (as mentioned in comments) Single()
and SingleOrDefault()
are the wrong methods to call. You would keep the same syntax, but call First()
and FirstOrDefault()
respectively.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With