Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way for retrieving single record results in LINQ to SQL

If I query a table with a condition on the key field as in:

        var user = from u in dc.Users                    where u.UserName == usn                    select u; 

I know that I will either get zero results or one result. Should I still go ahead and retrieve the results using a for-each or is there another preferred way to handle this kind of situation.

like image 964
Tony Peterson Avatar asked Oct 15 '08 13:10

Tony Peterson


People also ask

How LINQ queries converted into SQL queries?

LINQ to SQL translates the queries you write into equivalent SQL queries and sends them to the server for processing. More specifically, your application uses the LINQ to SQL API to request query execution. The LINQ to SQL provider then transforms the query into SQL text and delegates execution to the ADO provider.

What is the main channel of LINQ to SQL which retrieve objects from the database and resubmit changes?

The DataContext is the main gateway by which you retrieve objects from the database and resubmit changes.

Which is faster SQL or LINQ?

More importantly: when it comes to querying databases, LINQ is in most cases a significantly more productive querying language than SQL. Compared to SQL, LINQ is simpler, tidier, and higher-level.


1 Answers

Try something like this:

var user = (from u in dc.Users                    where u.UserName == usn                    select u).FirstOrDefault(); 

The FirstOrDefault method returns the first element of a sequence that satisfies a specified condition or a default value if no such element is found.

like image 176
Jorge Ferreira Avatar answered Sep 22 '22 13:09

Jorge Ferreira