Wednesday, March 6, 2013

LINQ to SQL

LINQ to SQL

.First() vs .FirstOrDefault()

I have an extra 30 mins for the day so I decided to make a quick blog about the first thing that I will remember from my early days of coding . For all you guys that is not that much familiar with LINQ or Language Integrated Query, let's just say that it's a feature introduced in Visual Studio 2008.

LINQ is defined by MSDN (link here http://msdn.microsoft.com/en-us/library/vstudio/bb397926.aspx) as

Language-Integrated Query (LINQ) is a set of features introduced in Visual Studio 2008 that extends powerful query capabilities to the language syntax of C# and Visual Basic. LINQ introduces standard, easily-learned patterns for querying and updating data, and the technology can be extended to support potentially any kind of data store.
In plain english, Linq queries will let you query in Visual Studio without defining any stored procedure or string connections. An example is as follows

A basic SQL select like below
Select name from table1 where table1.id=1
will look like this in LINQ
var name=(from p in datacontext.table1
where p.id=1
select p.name).FirstOrDefault();
If we use .First() and the result list is returned empty, LINQ will throw an error. It assumes by saying .First() that it will return a result for it's like saying SELECT TOP 1 in SQL.

Hope this helps someone!
-c0dem0nkey