<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>YTechie.com &#187; LINQ</title>
	<atom:link href="http://www.ytechie.com/category/linq/feed" rel="self" type="application/rss+xml" />
	<link>http://www.ytechie.com</link>
	<description>Productive software development using ASP.NET, C#, Adobe Flex, and other technologies and tools.</description>
	<lastBuildDate>Fri, 06 Nov 2009 21:16:21 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Speeding up data access by using Linq to SQL or EF</title>
		<link>http://www.ytechie.com/2009/10/speeding-up-data-access-by-using-linq-to-sql-or-ef.html</link>
		<comments>http://www.ytechie.com/2009/10/speeding-up-data-access-by-using-linq-to-sql-or-ef.html#comments</comments>
		<pubDate>Mon, 26 Oct 2009 20:53:53 +0000</pubDate>
		<dc:creator>superjason</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[entity framwork]]></category>
		<category><![CDATA[sql]]></category>

		<guid isPermaLink="false">http://www.ytechie.com/2009/10/speeding-up-data-access-by-using-linq-to-sql-or-ef.html</guid>
		<description><![CDATA[Recall that LINQ based object relational mappers (ORM) use expression trees to effectively translate your C# (or other language) LINQ code into SQL. Many DBA’s and developers that don’t fully understand this technology are often quick to discredit it. I’m going to show how significant performance, simplicity, and clarity can be gained by using Linq [...]]]></description>
			<content:encoded><![CDATA[<p>Recall that LINQ based object relational mappers (ORM) use expression trees to effectively translate your C# (or other language) LINQ code into SQL. Many DBA’s and developers that don’t fully understand this technology are often quick to discredit it. I’m going to show how significant performance, simplicity, and clarity can be gained by using Linq to SQL.</p>
<p>A recent DBA asked me the question “I thought inline SQL was bad, so why are we using it again?” LINQ may *smell* like inline SQL, but it is not. Let’s first take a look at some simple LINQ that is easy to read: </p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:0511d0cf-0c6f-4895-961f-7ab27960207d" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">from d in Devices
where d.CZone == 4
&amp;&amp; d.Type == "X"
select d.Id</pre>
</div>
<p>So how is this different than inline SQL? To be technical, you’re writing a query against a data model, with full intellisense. You’re also writing a provider agnostic query. This same query can be performed against SQL Server, Oracle, or even the Facebook API if there was a supporting framework in place. We now have a truly unified query architecture.</p>
<p>Let’s keep taking about this simple LINQ query, and see how you would write it if you didn’t want to use LINQ. Most developers before the days of LINQ would probably use a stored procedure. Stored procedures are great. They’re efficient, reusable, and easily updatable. Here is what it may look like:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:4e3748fa-09f3-42ae-9b35-05ea2bc23f29" class="wlWriterEditableSmartContent">
<pre name="code" class="sql">Create Procedure GetMyStuff
As
Select Id
From Devices
Where CZone = 4
And Type = 'X'
Select Id
GO</pre>
</div>
<p>A nice, simple SQL query. There are a few disadvantages that may not be immediately apparent:</p>
<ul>
<li>If you need a second, similar query, you have to either have to create and maintain two stored procedures. As an alternative, you could modify the stored procedure to operate differently based on a parameter. Both of these options are not idea, but LINQ does give us an alternative that I’ll discuss in a bit. </li>
<li>You don’t get intellisense when you’re writing your code. </li>
<li>You have to be concerned with two different “programming” paradigms, and also have to manually manage the translation in both directions. </li>
</ul>
<p>Now, let’s take our example to the other end of the spectrum, which will help show where LINQ can really shine where straight SQL does not. This example is a query for a search page. I set up a simple ASPX page to demonstrate. Here is a sample of the user interface:</p>
<p><a href="http://www.ytechie.com/post-images/2009/10/image.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.ytechie.com/post-images/2009/10/image_thumb.png" width="477" height="211" /></a> </p>
<p>The user enters a number of search criteria, and the results are displayed. I literally coded this in under 5 minutes. If you’re used to using stored procedures to retrieve this type of data, think about how you would go about creating this. You have a couple of options that I’m aware of:</p>
<ul>
<li>Write a separate stored procedure for every combination of parameters. In this case that would be 7 stored procedures. This would certainly not be ideal. </li>
<li>Write a single stored procedure that can handle each parameter as nullable parameters, and use “Where @Param Is Null Or Param = @Param”. This option is easy, but has some potential performance implications. </li>
<li>Write a single stored procedure that can handle each parameter as nullable parameter, and “If” statements to handle each scenario. This would be time consuming an error prone. </li>
</ul>
<p>In LINQ, we’re able to <strong>dynamically build up a query</strong>. For the search example, my LINQ looks like this:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:3f959401-5933-40c2-9b78-fdfdf1f457d9" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">var dataContext = new DataClassesDataContext();

var query = (IQueryable&lt;Device&gt;) dataContext.Devices;

if (txtCZone.Text.Length &gt; 0)
    query = query.Where(device =&gt; device.CZone == int.Parse(txtCZone.Text));
if (txtUCZone.Text.Length &gt; 0)
    query = query.Where(device =&gt; device.UCZone == int.Parse(txtUCZone.Text));
if (txtLZone.Text.Length &gt; 0)
    query = query.Where(device =&gt; device.LZone == int.Parse(txtLZone.Text));

dgResults.DataSource = query.ToList();
dgResults.DataBind();</pre>
</div>
<p>And of course we can use the query syntax instead (replacing lines 5-10 above):</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:bcfec0c3-d2bc-49b0-b45a-9878b8717f6f" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">if (txtCZone.Text.Length &gt; 0)
	query = from device in query where device.CZone == int.Parse(txtCZone.Text) select device;
if (txtUCZone.Text.Length &gt; 0)
	query = from device in query where device.UCZone == int.Parse(txtUCZone.Text) select device;
if (txtLZone.Text.Length &gt; 0)
	query = from device in query where device.LZone == int.Parse(txtLZone.Text) select device;</pre>
</div>
<p>The result is that the SQL code is specifically written to support only the parameters that the user has entered. No extra SQL, and no specific SQL to maintain. Remember that LINQ can be chained together without querying the underlying data. The actual querying of the data only occurs when enumerating the results, using an operation like “ToList()”.</p>
<p>To support paging we need to run 3 different types of underlying queries. Here is where LINQ is really going to shine. We can use the same base query for all of these operations, and not have to worry about the drastically different underlying SQL statements.</p>
<ol>
<li><strong>Result count</strong> &#8211; Simply by calling the “.Count()” method, we can retrieve the number of rows the query will return in total. The underlying SQL will be a simple and efficient <em>Count</em> operation. </li>
<li><strong>Page n query</strong> – By utilizing <em>Skip</em> and <em>Take</em>, any page within the results can be queried. The work of generating a common table expression is handled for you. </li>
<li><strong>First page query</strong> – If the underlying provider has an optimization for using the SQL <em>TOP</em> command, the first page of data you query will be able to avoid a common table expression. This has the advantage of being more efficient when the first (and often most common) page of results is displayed. </li>
</ol>
<p><strong>Real-world Results</strong></p>
<p>I initially ran into this in a real application that was primarily used to search through a large table of records. It had originally used the stored procedure approach, and was causing the entire system to slow down to the point of being unusable. Thanks to LINQ, we were able to make the search usable. In fact, the results were drastic:</p>
<table border="1" cellspacing="0" cellpadding="2" width="309" align="center">
<tbody>
<tr>
<td valign="top" width="66">&#160;</td>
<td valign="top" width="136"><strong>Stored Procedure</strong> </td>
<td valign="top" width="105"><strong>LINQ to SQL</strong> </td>
</tr>
<tr>
<td valign="top" width="66"><strong>Reads</strong></td>
<td valign="top" width="136">Over 4,000,000 </td>
<td valign="top" width="105">8948 </td>
</tr>
<tr>
<td valign="top" width="66"><strong>Duration</strong></td>
<td valign="top" width="136">3249ms </td>
<td valign="top" width="105">189ms </td>
</tr>
</tbody>
</table>
<p>In addition to the improved performance, the code was easier to maintain. The stored procedure was extremely cluttered, had large <em>where</em> clauses, and even contained two nearly identical copies of the query. One for calculating the count, and one for paging support.</p>
<p><strong>Conclusion</strong></p>
<p>LINQ gives us much more than “inline SQL”. It gives us a unified query syntax, delayed execution, query expression building, and dynamically created SQL output. Additionally, the generated queries are optimized based on the exact query being performed instead of making generic SQL that is optimized for multiple scenarios. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.ytechie.com/2009/10/speeding-up-data-access-by-using-linq-to-sql-or-ef.html/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>LINQ to SQL &amp; Entity Framework Pitfalls</title>
		<link>http://www.ytechie.com/2009/09/linq-to-sql-entity-framework-pitfalls.html</link>
		<comments>http://www.ytechie.com/2009/09/linq-to-sql-entity-framework-pitfalls.html#comments</comments>
		<pubDate>Thu, 01 Oct 2009 02:03:06 +0000</pubDate>
		<dc:creator>superjason</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[entity framwork]]></category>
		<category><![CDATA[sql]]></category>

		<guid isPermaLink="false">http://www.ytechie.com/2009/09/linq-to-sql-entity-framework-pitfalls.html</guid>
		<description><![CDATA[In my last post describing the differences between LINQ to objects and LINQ to SQL, I mentioned how LINQ to SQL and Entity Framework “interpret” your LINQ code, and create the corresponding SQL. Forgetting this fact is extremely dangerous, because LINQ to SQL and other object relational mappers are extremely leaky abstractions. LINQ is obviously [...]]]></description>
			<content:encoded><![CDATA[<p>In my last post describing the <a href="http://www.ytechie.com/2009/09/understanding-linq-and-linq-to-sql-and-ef.html">differences between LINQ to objects and LINQ to SQL</a>, I mentioned how LINQ to SQL and Entity Framework “interpret” your LINQ code, and create the corresponding SQL. Forgetting this fact is extremely dangerous, because LINQ to SQL and other object relational mappers are extremely leaky abstractions. LINQ is obviously a wonderful technology, but this post will be talking about some potential pitfalls you may run into.</p>
<p><strong>SQL Query Complexity Disproportional to LINQ Complexity</strong></p>
<p>Recall the example from my last post:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:5641d3eb-6590-4d9a-8cac-c0db294cd564" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">//Query Syntax:
from device in Devices
where device.Type != null
select device.DeviceId

//SQL Syntax:
SELECT [t0].[DeviceId]
FROM [Devices] AS [t0]
WHERE [t0].[Type] IS NOT NULL</pre>
</div>
<p>In this case, LINQ to SQL has done something wonderful. It’s saved us from having to understand or worry about the translation of syntax between C# and SQL. Now, what happens when we write something a little more advanced, such as a nested group by?</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:62df480a-95e2-4910-95b5-9ec5eb45f0be" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">from d in Devices
group d by d.CZone into czoneGroup
select new { Key = czoneGroup.Key, val = from d2 in czoneGroup
	group d2 by d2.LZone into lzoneGroup
	select lzoneGroup.Key }</pre>
</div>
<p>And the corresponding SQL:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:f50bc355-9467-4d6a-9aaa-63ff31cecff9" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">SELECT [t0].[CZone] AS [Key]
FROM [Devices] AS [t0]
GROUP BY [t0].[CZone]
GO

DECLARE @x1 Int = 3
SELECT [t0].[LZone]
FROM [Devices] AS [t0]
WHERE ((@x1 IS NULL) AND ([t0].[CZone] IS NULL)) OR ((@x1 IS NOT NULL) AND ([t0].[CZone] IS NOT NULL) AND (@x1 = [t0].[CZone]))
GROUP BY [t0].[LZone]
GO

DECLARE @x1 Int = 1
SELECT [t0].[LZone]
FROM [Devices] AS [t0]
WHERE ((@x1 IS NULL) AND ([t0].[CZone] IS NULL)) OR ((@x1 IS NOT NULL) AND ([t0].[CZone] IS NOT NULL) AND (@x1 = [t0].[CZone]))
GROUP BY [t0].[LZone]
GO

//Reminaing SQL removed....</pre>
</div>
<p>What just happened? Our innocent nested join has turned into a monster! This is an example of a query that is simple to do in LINQ, but has no translation to a simple SQL statement. Instead of just bombing, the LINQ to SQL engine comes up with a solution that a user may not have written themselves. A typical SQL developer may have looked for a different approach.</p>
<p><em>Side note: In the nested group-by, notice that LINQ to SQL uses multiple queries. This differs from the Entity Framework approach, which uses outer joins to achieve the same effect.</em></p>
<p>Does it matter? The answer isn’t so simple. In this simplified example, the performance impact is minimal. Unfortunately, with a large amount of data in this type of query, you could start to experience terrible performance. I personally saw a nested query that was only a few lines of code turn into a 27 page SQL statement. The SQL statement was technically correct, but took seconds to execute, when it should have taken a fraction of a second.</p>
<p>One simple solution that I have found to be very effective, yet not intuitive, is breaking apart the initial query and forcing it to execute using the ToList() method. You’ll have to have a decent “where” clause to avoid excessive amounts of data being returned. Once we have the raw data, LINQ to objects will provide us the same set of tools to further manipulate our data. For instance, here is a modified version of the example presented earlier:</p>
</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:fe1b1c69-41cf-42f9-9ab2-feed64283c70" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">//Simple &amp; fast initial query from the database
var rawData = (from d in Devices
where d.Location = 'B3').ToList();

//This operation happens "disconnected"
var results = from d in rawData
group d by d.CZone into czoneGroup
select new { Key = czoneGroup.Key, val = from d2 in czoneGroup
	group d2 by d2.LZone into lzoneGroup
	select lzoneGroup.Key };</pre>
</div>
<p>The reason this works well is that it’s taking advantage of the strength of SQL Server, which is to query data, and the strength of .NET, which is to process and manipulate data.</p>
<p><strong>LINQ Abstracting Away Problems it Can’t Solve</strong></p>
<p>Here is a simplified version of a query I saw recently:</p>
</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:6b58a736-2368-485e-ad30-4726c9267ae1" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">int sum = (from d in Devices
where 1 == 2 &amp;&amp; d.CZone != null
select d.CZone.Value).Sum()</pre>
</div>
<p>To make it extremely clear what I’m trying to accomplish, I put “1 == 2” in the “where” clause, so that no rows match the condition. The “Sum()” method returns the type that it’s acting on. For example, if you’re summing integers, the result is an integer. If you’re summing nullable integers, the result is a nullable integer. This is perfectly valid LINQ. This is effectively the SQL that is generated (I simplified it for clarity):</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:8e0404af-4082-4891-80e6-4e96545bd024" class="wlWriterEditableSmartContent">
<pre name="code" class="sql">Select SUM(CZone)
From Devices
Where 1 = 2</pre>
</div>
<p>Since the result of this SQL statement is NULL, it can’t be converted back to an integer. The exception is “<em>InvalidOperationException: The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type.</em>”</p>
<p>When the LINQ is translated to SQL, there is no such operation as converting a nullable value to a non-nullable, so the “.Value” operation is ignored. This would be fine if the sum function still expected a nullable return type, but it’s now expecting an integer. When it can’t find any rows to return, it tries to return NULL. Since it’s trying to package up a NULL value into a standard integer type, it has no choice but to throw an exception.</p>
<p><strong>Conclusion</strong></p>
<p>Getting started with LINQ is fairly straightforward, but you can’t forget the fact that whatever query you’re writing must be converted into a SQL statement, and the results must be converted back to data that is understandable to .NET. Every LINQ query you write should be checked with a tool such as <a href="http://www.linqpad.net/" rel="nofollow" onclick="pageTracker._trackPageview('/outgoing/www.linqpad.net/?referer=');">LINQPad</a> to ensure that the SQL is efficient, and matches what you expect.</p>
<p>Also keep in mind that when you upgrade your data provider, your queries can change. For example, converting a statement from LINQ to SQL to Entity Framework can generate different SQL queries, just as updating to a newer version of the same ORM can.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ytechie.com/2009/09/linq-to-sql-entity-framework-pitfalls.html/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Understanding LINQ and LINQ to SQL (and EF)</title>
		<link>http://www.ytechie.com/2009/09/understanding-linq-and-linq-to-sql-and-ef.html</link>
		<comments>http://www.ytechie.com/2009/09/understanding-linq-and-linq-to-sql-and-ef.html#comments</comments>
		<pubDate>Thu, 17 Sep 2009 15:17:44 +0000</pubDate>
		<dc:creator>superjason</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[entity framwork]]></category>

		<guid isPermaLink="false">http://www.ytechie.com/2009/09/understanding-linq-and-linq-to-sql-and-ef.html</guid>
		<description><![CDATA[Back to basics for this post. Developers often throw around the word LINQ when talking about a number of different technologies. Now that I have been comfortably using a wide variety of LINQ technologies for a fair amount of time, I’m now able to convey some of the key differences that are critical to using [...]]]></description>
			<content:encoded><![CDATA[<p>Back to basics for this post. Developers often throw around the word LINQ when talking about a number of different technologies. Now that I have been comfortably using a wide variety of LINQ technologies for a fair amount of time, I’m now able to convey some of the key differences that are critical to using LINQ technologies efficiently. I’m also using this as a foundation and reference for some exciting upcoming posts.</p>
<p>The first key point is to know what the heck LINQ is. LINQ itself is a number of separate features. One of these key features is being able to write SQL-like syntax (query syntax) in your code. At a basic level, that’s all you need to know for now.</p>
<p><strong>LINQ (to objects)</strong></p>
<p>First, we’re going to talk about LINQ to objects, which I typically just refer to as LINQ (possibly making the matter more confusing). It has absolutely nothing to do with SQL Server, Oracle, or any other kind of relational database. I’m talking about LINQ to objects, because I think that understanding it and contrasting it with LINQ to SQL is critical to understanding both.</p>
<p>For a moment, forget that LINQ exists. Let’s say that you wanted to filter a list of names, to only get names that start with the letter “J”. You could write the following “utility” function: (if you don’t understand <a href="http://www.ytechie.com/2009/02/using-c-yield-for-readability-and-performance.html">“yield return”, see this post on that topic</a>).</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:74dcd1eb-c170-4d76-b6e8-441fc9f40dba" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">public static IEnumerable&lt;string&gt; GetNamesStartingWithJ(IEnumerable&lt;string&gt; names)
{
    foreach(var name in names)
        if(name.StartsWith("J"))
            yield return name;
}</pre>
</div>
<p>A new feature in C# introduced in .NET 3.0, is a concept known as an extension method. This lets us turn my handy dandy static utility method into a method that can be called on a list of names. By changing the signature to this:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:b27c9cbc-7f0a-4fb5-be05-8f5946380254" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">public static IEnumerable&lt;string&gt; GetNamesStartingWithJ(this IEnumerable&lt;string&gt; names)</pre>
</div>
<p>I can then call it like this (Sweet!):</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:9b70c490-45ef-40a4-903b-4cbd3b3470ed" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">var myListOfNames = new List&lt;T&gt; {"Abe", "Jack", "Jason"};
var jNames = myListOfNames.GetNamesStartingWithJ();</pre>
</div>
<p>We haven’t even talked about LINQ yet, but we’ve basically reinvented a portion of it. As an exercise for the reader, think about how you could use a Lambda parameter to pass in a filter criteria to create a &quot;.Where” method. All the pieces are in place to re-create this form of LINQ yourself.</p>
<p>One actual new feature for LINQ is known as query syntax. Basically, it gives us an alternative way to write our query. It makes the code look more like SQL, and less like a long chain of extension methods.</p>
<p>Lambda Syntax:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:a76b3655-6a72-4fa3-b147-38bfd8dedf80" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">var uppercaseJNames = names.Where(name =&gt; name.StartsWith("J")).Select(name =&gt; name.ToUpper());</pre>
</div>
<p>Query Syntax (same query):</p>
<p><div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:7e10587a-ba5f-4062-bba8-cab816b7eb3e" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">var uppercaseJNames = from name in names
	where name.StartsWith("J")
	select name.ToUpper();</pre>
</div>
<p>In both of those examples, the exact same operations are occurring, and you get the result. The one you choose will most likely come down to personal preference. It’s also worth noting that some of the extension methods provided out of the box are not available in query syntax. You can either avoid the query syntax in those cases, or use a hybrid approach.</p>
<p><strong>How is LINQ to SQL (and Entity Framework, etc) Different?</strong></p>
<p>Now, I hope you understand that there isn’t really any magic going on in LINQ. Microsoft has simply given us a new set of easy to use tools that make working with sets a breeze.</p>
<p>LINQ to SQL is a different matter. Instead of executing code, you’re building an expression. An expression is simply a “picture” of what you’re trying to accomplish. It can interpreted in many different ways. To understand the underlying technology, you’ll have to read up on expression trees, which I’m intentionally keeping outside the scope of this post.</p>
<p>If we have a “picture” of a query, what happens to it when we want to “run” it? LINQ to SQL, Entity Framework, and other LINQ implementations look at your query, and basically translate it into something else. How about an example?:</p>
<p><div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:fc8658fb-f565-47dc-af0c-f5c4007c3a89" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">//Query Syntax
var deviceIds = from device in Devices
where device.Type == "I"
select device.DeviceId

//Lambda Sytax (extension methods)
var deviceIds = Devices
   .Where (device =&gt; (device.Type == "I"))
   .Select (device =&gt; device.DeviceId)

//SQL
SELECT [t0].[DeviceId]
FROM [Devices] AS [t0]
WHERE [t0].[Type] = "I"</pre>
</div>
<p>I’ve provided the query syntax and the lambda syntax. At the bottom is the resulting translation into a SQL statement.</p>
<p>In this last example, I’ll try to make it clear that your code is simply interpreted and translated:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:a87dc611-83a7-4e29-ad97-f2b3ecff5f57" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">//Query Syntax:
from device in Devices
where device.Type != null
select device.DeviceId

//SQL Syntax:
SELECT [t0].[DeviceId]
FROM [Devices] AS [t0]
WHERE [t0].[Type] IS NOT NULL</pre>
</div>
<p>Notice that the C# operator “!=” translates in SQL to “IS NOT NULL”. This was handled automatically for us. Our expression did NOT get back all the rows and apply a conditional to it.</p>
<p>Why is this important? To use either technology effectively, you have to understand that when you’re working with objects, it’s simply a chain of methods, and often behaves as you would expect. When working with LINQ to SQL (or a related technology), the expression is evaluated, and might not execute like you expected.</p>
<p>Understanding the internal workings of these technologies will let us fully take advantage of all the wonderful features it has to offer. In upcoming posts, I’ll be warning you of some potential pitfalls related to how your queries are interpreted and translated. I’ll also be showing you how to get significant performance gains by using LINQ to SQL or Entity Framework efficiently (over traditional SQL based solutions). I’ll also be showing you how I write LINQ queries to query an AutoCAD document!</p>
<p>Related Posts:</p>
<ul>
<li><a href="http://www.ytechie.com/2009/02/using-c-yield-for-readability-and-performance.html">Using Yield Return for readability and performance</a></li>
<li><a href="http://www.ytechie.com/2008/06/using-var-to-simplify-code-and-avoid-redundancy.html">Using “var” to simplify code and avoid redundancy</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.ytechie.com/2009/09/understanding-linq-and-linq-to-sql-and-ef.html/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Delayed execution vs ToList() in LINQ Database Queries</title>
		<link>http://www.ytechie.com/2009/06/delayed-execution-vs-tolist-in-linq-database-queries.html</link>
		<comments>http://www.ytechie.com/2009/06/delayed-execution-vs-tolist-in-linq-database-queries.html#comments</comments>
		<pubDate>Tue, 23 Jun 2009 16:46:31 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[entity framwork]]></category>

		<guid isPermaLink="false">http://www.ytechie.com/2009/06/delayed-execution-vs-tolist-in-linq-database-queries.html</guid>
		<description><![CDATA[LINQ to SQL and Entity framework allow us to build a query, which gets translated into an expression tree, and executed once the full query is built. The beauty is that we can build up a query using multiple expressions and Lambdas, without actually querying the data. Since these types of queries are delay loaded, [...]]]></description>
			<content:encoded><![CDATA[<p>LINQ to SQL and Entity framework allow us to build a query, which gets translated into an expression tree, and executed once the full query is built. The beauty is that we can build up a query using multiple expressions and Lambdas, without actually querying the data. Since these types of queries are delay loaded, why not avoid executing them until the last possible moment? Read on to see why this is usually a bad idea.</p>
<p>First, let’s take a look the code for a repository method that builds a query, executes the query, and returns the results in a list:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:3a31321f-f9b9-4c17-91c2-43d838b3f22a" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">public IEnumerable&lt;Cat&gt; FindAllCats()
{
	var query = from c in db.Cats
		select c;

	return query.ToList();
}</pre>
</div>
<p align="center"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Execute in Repository" border="0" alt="Execute in Repository" src="http://www.ytechie.com/post-images/2009/06/image1.png" width="486" height="142" /> </p>
<p>The “ToList” is forcing the IQueryable&lt;Cat&gt; query to execute and put the results in a list <strong>immediately</strong>. However, we know that IQueryable&lt;T&gt; inherits from IEnumerable&lt;T&gt;, so what happens if we avoid the list creation completely?</p>
</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:10d24797-5a70-435a-85bc-c076fe3c457b" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">public IEnumerable&lt;Cat&gt; FindAllCats()
{
	var query = from c in db.Cats
		select c;

	return query;
}</pre>
</div>
<p align="center"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Execute in UI" border="0" alt="Execute in UI" src="http://www.ytechie.com/post-images/2009/06/image2.png" width="486" height="142" /></p>
<p align="left">In this scenario, our method is returning the same interface, but the underlying type is now a LINQ database iterator instead of a List&lt;T&gt;.</p>
<p><strong>Delaying execution can lead to</strong> <strong><em>multiple</em></strong> <strong>executions</strong></p>
<p>If the code is not explicitly putting the results into a list, we’re actually passing back a form of an iterator. This works great if we only need to execute the query once. However, if we iterate through the list more than once, <strong>we actually end up executing our query multiple times</strong>. This can obviously lead to poor performance.</p>
<p>If you’re writing fast queries, you may not even notice if they’re being called too many times. However, there may be a worse problem lurking in your code. <strong>Each time you iterate through the enumerator, you’re getting a different set of objects</strong>. The same query is being made with the same results, but the objects are re-built each time. This leads to objects that are <strong>equivalent, but not the same</strong>. For example, you may get back Cat objects with the names “Bill” and “Ted”, but if you actually check them for equality using “==”, they will not be the same object <strong>instance</strong>. <font color="#ff0000"><strong>Correction: Scott points out in the comments that this isn’t necessarily the case. Keep in mind that it can still occur if projecting types and not working with the original objects.</strong></font></p>
<p><strong>Delaying execution may mean you no longer have a database connection when attempting to execute the query</strong></p>
</p>
<p>If you delegate the task of initiating your query to another layer, you better be sure that the database connection is still around, and is in a queryable state. If you’re using the standard repository pattern and a short-lived database connection pattern, you may quickly run into problems when you try to iterate through the results of the enumerator you receive from your repository layer.</p>
<p><strong>Conclusion</strong></p>
<p>If you’re thinking about moving the execution of your queries to another layer, make sure you understand the consequences. You’ll need to weigh those consequences against the tiny benefit that you’ll receive from the delayed execution. There may be cases where delaying the execution or possibly avoiding it completely will improve your application, but those are probably very rare cases.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ytechie.com/2009/06/delayed-execution-vs-tolist-in-linq-database-queries.html/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Unit Testing a LINQ to SQL or EF Query</title>
		<link>http://www.ytechie.com/2009/04/unit-testing-a-linq-to-sql-or-ef-query.html</link>
		<comments>http://www.ytechie.com/2009/04/unit-testing-a-linq-to-sql-or-ef-query.html#comments</comments>
		<pubDate>Thu, 09 Apr 2009 18:58:30 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://www.ytechie.com/2009/04/unit-testing-a-linq-to-sql-or-ef-query.html</guid>
		<description><![CDATA[I was writing a slightly non-trivial method to query a database to find a record matching a certain time range. It quickly became clear that it would be nice to write some automated unit tests against it. Integration tests would be less than ideal because of the execution time and complexity. I ended up with [...]]]></description>
			<content:encoded><![CDATA[<p>I was writing a slightly non-trivial method to query a database to find a record matching a certain time range. It quickly became clear that it would be nice to write some automated unit tests against it. Integration tests would be less than ideal because of the execution time and complexity. I ended up with a way to test the code without jumping through too many hoops.</p>
<p><strong>IEnumerable vs IQueryable</strong></p>
<p>First, you need to understand the purpose of IEnumerable and IQueryable. IEnumerable defines a stream of objects that can be retrieved sequentially. It’s implemented for nearly every type of list, and it’s an integral part of LINQ. There are now methods included such as “Where” and “Select” that let us filter, sort, and manipulate lists of data in interesting yet simple ways. This can also be referred to as LINQ to objects.</p>
<p>IQueryable inherits from IEnumerable, and is designed to be translatable into a query. IQueryable is typically used to build an expression tree that <strong>represents</strong> the requested operations. The operations are not actually executed until the expression tree is evaluated and used.</p>
<p>As an example, let’s say I have a database with a table and entities called DateRange. Suppose I cast the DateRange entityset (which implements IQueryable&lt;DateRange&gt;) as IEnumerable&lt;DateRange&gt;. When I call LINQ expressions on that IEnumerable, the underlying query is run immediately, which effectively causes all of the data from that table to be retrieved. If I use IQueryable without casting, my operations get turned into SQL that gets executed when I actually try to iterate through the data (probably using ToList() or foreach). It’s obviously preferable to have the query run in SQL since it can more efficiently filter the data.</p>
<p><strong>The Problem</strong></p>
<p>As I mentioned earlier, I recently starting writing a data access method that started to contain some non-trivial logic. Whenever I see logic, I want to be able to unit test it! I ended up pulling out the logic into its own static method. This method takes in IEnumerable&lt;DateRange&gt;, which can also accept IQueryable&lt;DateRange&gt; (because of the inheritance, you’ll recall). Then, I simply use the AsQueryable method in IEnumerable. This ends up building the needed expression tree that can be translated into a SQL query, but it also lets me test against an in memory collection.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:fa00aac0-6c39-4e4b-bc9f-a7781d500240" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">public static DateRange FindRelativeToDate(IEnumerable&lt;DateRange&gt; enumerable, DateTime reference, int periodOffset)
{
	//Build as an expression tree, if possible, otherwise enumerate
	var queryable = enumerable.AsQueryable();

	//Now put in all the logic

	var reference2 = reference.AddDays(-1);

	var initialRange = from bp in queryable
		 where reference &gt;= bp.Start &amp;&amp; reference2 &lt; bp.End
		 select bp;

	var currentDateRange = initialRange.First();

	if(periodOffset == 0)
		return currentDateRange;

	var newRange = from bp in queryable
		select bp;

	if (periodOffset &gt; 0)
	{
		newRange = newRange.Where(x =&gt; x.Start &gt;= currentDateRange.Start);
		newRange = newRange.OrderBy(x =&gt; x.Start);
	}
	else
	{
		newRange = newRange.Where(x =&gt; x.End &lt;= currentDateRange.End);
		newRange = newRange.OrderByDescending(x =&gt; x.Start);
	}

	return newRange.Skip(Math.Abs(periodOffset)).Take(1).FirstOrDefault();
}</pre>
</div>
<p>In my unit test class, I can define a list of sample data. I took real data from the database to make the tests as close to reality as possible:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:04d1e3b3-50b1-48e5-931a-eb3c96fa191e" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">private static readonly List&lt;DateRange&gt; _DateRanges = new List&lt;DateRange&gt;
{
	new DateRange {Start = new DateTime(2009, 1, 1), End = new DateTime(2009, 1, 30)},
					new DateRange {Start = new DateTime(2009, 1, 31), End = new DateTime(2009, 3, 01)},
					new DateRange {Start = new DateTime(2009, 3, 2), End = new DateTime(2009, 3, 31)},
					new DateRange {Start = new DateTime(2009, 4, 1), End = new DateTime(2009, 4, 30)},
};</pre>
</div>
<p>Now, I can easily test the static class I wrote (this is 1 of 9+ real tests):</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:44884bb7-a315-4cd2-a693-f699e9d4e34a" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">[TestMethod]
public void FindRelativeToDate_MiddleOfDateRange_ContainingDateRange()
{
	var result = DateRangeRepository.FindRelativeToDate(_DateRanges, new DateTime(2009, 3, 15), 0);
	Assert.AreEqual(_DateRanges[2], result);
}</pre>
</div>
<p>The only thing that is left to do is wire up the repository method so that it calls my static method. This is a thin wrapper layer that will actually get used in production. If you run profiler, you’ll see that the query expression is being evaluated and converted into an efficient SQL expression.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:ad5a6773-4fc7-435a-b3f1-f68cc877ff64" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">public DateRange FindRelativeToDate(DateTime reference, int periodOffset)
{
	var ctx = dbEntities;
	return FindRelativeToDate(ctx.DateRangeSet, reference, periodOffset);
}</pre>
</div>
<p><strong>Limitations/Conclusion</strong></p>
<p>Unfortunately, this method of testing a repository doesn’t scale easily. If you start working with multiple entity sets that are combined with join operations, this technique is next to impossible to use. You’ll see the most benefit when working with a single entity type, and need to test logic in your repository method.</p>
<p>One thing you need to be aware of, is that LINQ to SQL and Entity Framework don’t implement every IQueryable/IEnumerable method. This means that you could potentially make calls on the in-memory collection that will then fail when you use the actual database. Fortunately, these problems can usually be detected fairly quickly.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ytechie.com/2009/04/unit-testing-a-linq-to-sql-or-ef-query.html/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
