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.
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.
The DataContext is the main gateway by which you retrieve objects from the database and resubmit changes.
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.
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.
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