<?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>.Net Smoothie &#187; LINQ</title>
	<atom:link href="http://www.richardbushnell.net/category/linq/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.richardbushnell.net</link>
	<description></description>
	<lastBuildDate>Wed, 30 Dec 2009 11:42:52 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Easy Data-loading with LINQ-to-SQL and LINQ-to-XML</title>
		<link>http://www.richardbushnell.net/2008/03/20/easy-data-loading-with-linq-to-sql-and-linq-to-xml-4/</link>
		<comments>http://www.richardbushnell.net/2008/03/20/easy-data-loading-with-linq-to-sql-and-linq-to-xml-4/#comments</comments>
		<pubDate>Thu, 20 Mar 2008 07:53:48 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[LINQ to SQL]]></category>
		<category><![CDATA[LINQ-to-XML]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[VB.Net]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[data]]></category>
		<category><![CDATA[loading]]></category>
		<category><![CDATA[VB]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://richardbushnell.net/index.php/2008/03/20/easy-data-loading-with-linq-to-sql-and-linq-to-xml-4/</guid>
		<description><![CDATA[.Net 3.5 had some nice tricks in it. LINQ-to-XML was one of them. With the new &#34;X&#34;-types, you can make working with XML really easy. VB.Net 9 takes it one step further, and lets you write XML in your code without strings. &#34;Hey Rich, that&#8217;s old news,&#34; I hear you say. &#34;And who&#8217;s interested in [...]]]></description>
			<content:encoded><![CDATA[
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F03%2F20%2Feasy-data-loading-with-linq-to-sql-and-linq-to-xml-4%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<br><p>.Net 3.5 had some nice tricks in it. LINQ-to-XML was one of them. With the new &quot;X&quot;-types, you can make working with XML really easy. </p>
<p>VB.Net 9 takes it one step further, and lets you write XML in your code without strings.</p>
<p>&quot;Hey Rich, that&#8217;s old news,&quot; I hear you say. &quot;And who&#8217;s interested in VB today anyway?&quot;</p>
<p>Well, apparently there are a lot of VB-er&#8217;s still out there. I am mainly a C# developer myself, but I found that VB was perfect for a problem I had recently -&#160; loading of XML data into a SQL Server table.</p>
<p><span id="more-98"></span></p>
<h2>SQL Server 2005 and XML Fields</h2>
<p>I recently came across the need to load a database with XML data fields in SQL Server 2005. I had a series of XML documents which all needed to be pumped into a table containing a field of type XML. I could have opened up SQL Server Management Studio and fired in a load of strings, but I was a bit concerned that the XML might not be formatted quite correctly, which would have caused problems in the loading process.</p>
<p>Another problem was that I wanted to be able to add dynamic XML. I wanted to generate some XML data on the fly. That&#8217;s not so easy with insert statements in SQL.</p>
<h2>LINQ-to-SQL and XML Fields</h2>
<p>Using my recently-acquired LINQ-to-SQL knowledge, I knew that the Entities generated for an XML field are translated to <strong>XElements</strong> &#8211; the new XML type in .Net 3.5. I also knew that VB 9 lets you create an <strong>XElement</strong> by using XML in code itself: </p>
<p><a href="http://www.richardbushnell.net/wp-content/uploads/2008/03/image15.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="200" alt="image" src="http://www.richardbushnell.net/wp-content/uploads/2008/03/image-thumb11.png" width="445" border="0" /></a>&#160;</p>
<p>So I came up with a plan&#8230;</p>
<h2>Inserts with LINQ-to-SQL</h2>
<p>For data-loading, LINQ-to-SQL is magic. A simple Insert is a piece of cake.</p>
<p>First, create your <strong>DataContext</strong> using the Visual Studio template, then drag the table you are inserting to onto the <strong>DataContext</strong> canvas. That gives you an Entity class. You then can create an Entity in your code, call <strong>InsertOnSubmit</strong> on the <strong>DataContext</strong> table, then call <strong>SubmitChanges</strong> on the <strong>DataContext</strong> itself.</p>
<p>Using Object Property Initializers, you can make this really easy.</p>
<p>Here&#8217;s what it looks like with VB.Net using an XML datatype:</p>
<p><a href="http://www.richardbushnell.net/wp-content/uploads/2008/03/image13.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="631" alt="image" src="http://www.richardbushnell.net/wp-content/uploads/2008/03/image-thumb9.png" width="475" border="0" /></a> </p>
<p>(Sorry to have torn the edge off the code there, but it wouldn&#8217;t fit nicely in my post at full width. XML can be a <em>little </em>long sometimes.)</p>
<p>The great thing here is that any malformed XML is highlighted (or even automatically corrected) for me by the VB compiler. I can also add parameters and generate lots of different XML using the familiar ASP syntax:</p>
<div style="width:480px;margin-right:100px">
<p><a href="http://www.richardbushnell.net/wp-content/uploads/2008/03/image14.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="112" alt="image" src="http://www.richardbushnell.net/wp-content/uploads/2008/03/image-thumb10.png" width="374" border="0" /></a>&#160;</p>
</div>
<div style="clear:left">
<p>And as <strong>SubmitChanges</strong> uses a single transaction, the data-loading can easily be an all-or-nothing affair. In addition, any foreign key relationships can easily be taken care of by assigning objects to each other using standard object notation. The <strong>DataContext</strong> takes care of doing things in the correct order for you.</p>
</div>
<p>It&#8217;s all super-easy, and takes about 1 minute to get started.</p>

<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F03%2F20%2Feasy-data-loading-with-linq-to-sql-and-linq-to-xml-4%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
]]></content:encoded>
			<wfw:commentRss>http://www.richardbushnell.net/2008/03/20/easy-data-loading-with-linq-to-sql-and-linq-to-xml-4/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Design Guidelines for LINQ</title>
		<link>http://www.richardbushnell.net/2008/03/13/design-guidelines-for-linq/</link>
		<comments>http://www.richardbushnell.net/2008/03/13/design-guidelines-for-linq/#comments</comments>
		<pubDate>Thu, 13 Mar 2008 18:40:24 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Extension Methods]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Guidelines]]></category>

		<guid isPermaLink="false">http://richardbushnell.net/index.php/2008/03/13/design-guidelines-for-linq/</guid>
		<description><![CDATA[Have you wondered if and when you should use the new LINQ features in .Net 3.5? Like, where should I put a new extension method? Should I use Func&#60;T&#62; or a custom delegate? How do I best implement a mix-in (extension methods on an interface)? Well, Mircea Trofin has just published a new draft of [...]]]></description>
			<content:encoded><![CDATA[
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F03%2F13%2Fdesign-guidelines-for-linq%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<br><p>Have you wondered if and when you should use the new LINQ features in .Net 3.5?</p>
<p>Like, where should I put a new extension method? Should I use Func&lt;T&gt; or a custom delegate? How do I best implement a mix-in (extension methods on an interface)?</p>
<p>Well, Mircea Trofin has just published a new draft of some <a href="http://blogs.msdn.com/mirceat/archive/2008/03/13/linq-framework-design-guidelines.aspx" target="_blank">LINQ design guidelines</a>. You might just find your answers there.</p>

<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F03%2F13%2Fdesign-guidelines-for-linq%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
]]></content:encoded>
			<wfw:commentRss>http://www.richardbushnell.net/2008/03/13/design-guidelines-for-linq/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>LINQ or DIE</title>
		<link>http://www.richardbushnell.net/2008/03/03/linq-or-die/</link>
		<comments>http://www.richardbushnell.net/2008/03/03/linq-or-die/#comments</comments>
		<pubDate>Mon, 03 Mar 2008 14:51:59 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[LINQ to SQL]]></category>
		<category><![CDATA[Pro LINQ]]></category>
		<category><![CDATA[SQLMetal]]></category>

		<guid isPermaLink="false">http://richardbushnell.net/index.php/2008/03/03/linq-or-die/</guid>
		<description><![CDATA[I just read a fantastic quote about LINQ from the book Pro LINQ: Language Integrated Query in C# 2008 by Joseph C. Rattz, Jr.: I prefer to think of LINQ as a data iteration engine, but perhaps Microsoft didn&#8217;t want a technology named DIE. I think they already built the technology for such a product, [...]]]></description>
			<content:encoded><![CDATA[
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F03%2F03%2Flinq-or-die%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<br><div>
<p><a href="http://www.amazon.com/gp/product/1590597893?ie=UTF8&amp;tag=netsmoo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=1590597893"><img style="margin: 0px 20px 20px 0px" src="/images/21Nhb9ibKjL._AA_SL160_.jpg" align="left" border="0" /></a><img style="margin: 0px; border-top-style: none! important; border-right-style: none! important; border-left-style: none! important; border-bottom-style: none! important" height="1" alt="" src="http://www.assoc-amazon.com/e/ir?t=netsmoo-20&amp;l=as2&amp;o=1&amp;a=1590597893" width="1" border="0" /> </p>
</p></div>
<p>I just read a fantastic quote about LINQ from the book <a href="http://www.amazon.com/gp/product/1590597893?ie=UTF8&amp;tag=netsmoo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=1590597893">Pro LINQ: Language Integrated Query in C# 2008</a><img style="margin: 0px; width: 1px; border-top-style: none! important; border-right-style: none! important; border-left-style: none! important; border-bottom-style: none! important" height="1" alt="" src="http://www.assoc-amazon.com/e/ir?t=netsmoo-20&amp;l=as2&amp;o=1&amp;a=1590597893" width="1" border="0" /> by <a href="http://www.linqdev.com/PublicPortal/publicportal/blog.aspx?EntryID=28">Joseph C. Rattz, Jr.:</a></p>
<blockquote><p>I prefer to think of LINQ as a data iteration engine, but perhaps Microsoft didn&#8217;t want a technology named DIE.</p>
</blockquote>
<p>I think they already built the technology for such a product, and put it in Vista. <img src='http://www.richardbushnell.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>It&#8217;s a great book. The first LINQ book I&#8217;ve found with a really detailed explanation of LINQ-to-SQL and the SQLMetal generation tool.</p>

<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F03%2F03%2Flinq-or-die%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
]]></content:encoded>
			<wfw:commentRss>http://www.richardbushnell.net/2008/03/03/linq-or-die/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The LinqDataSource and the Hidden Viewstate</title>
		<link>http://www.richardbushnell.net/2008/02/21/the-linqdatasource-and-the-hidden-viewstate/</link>
		<comments>http://www.richardbushnell.net/2008/02/21/the-linqdatasource-and-the-hidden-viewstate/#comments</comments>
		<pubDate>Thu, 21 Feb 2008 08:00:03 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Quaility]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[LINQ to SQL]]></category>
		<category><![CDATA[LinqDataSource]]></category>
		<category><![CDATA[ViewState]]></category>

		<guid isPermaLink="false">http://richardbushnell.net/index.php/2008/02/21/the-linqdatasource-and-the-hidden-viewstate/</guid>
		<description><![CDATA[Yesterday I thought I&#8217;d learn about the LinqDataSource in ASP.Net 3.5, and got an interesting surprise. The new LinqDataSource can also be used with a LINQ-to-SQL model to perform updates. You simply add the DataSource to your page, set the table name, and set EnableUpdate to true. Then, using a standard DataControl, you can make [...]]]></description>
			<content:encoded><![CDATA[
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F02%2F21%2Fthe-linqdatasource-and-the-hidden-viewstate%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<br><p>Yesterday I thought I&#8217;d learn about the <strong>LinqDataSource</strong> in ASP.Net 3.5, and got an interesting surprise.</p>
<p>The new <strong>LinqDataSource</strong> can also be used with a LINQ-to-SQL model to perform updates. You simply add the <strong>DataSource</strong> to your page, set the table name, and set <strong>EnableUpdate</strong> to true. Then, using a standard <strong>DataControl</strong>, you can make updates to your data entities.</p>
<p>The question is, how does this work? It appears to be a bit magical. <span id="more-55"></span></p>
<h2>The Magic of LINQ</h2>
<p>In a <a href="http://richardbushnell.net/index.php/2008/02/18/how-to-update-data-with-linq-to-sql/">previous post</a>, I mentioned that LINQ-to-SQL updates can be done in two ways: either you make a call to retrieve a row, then update it, or you provide known values for all fields and try to update using optimistic concurrency.</p>
<p>If the <strong>LinqDataSource</strong> used the first technique, the performance might be bad. Plus, it would have to only update those fields that had been updated by the <strong>DataControl</strong>, and ignore the rest. That wouldn&#8217;t make sense, so I correctly supposed that was not what was happening.</p>
<p>It makes more sense that the <strong>LinqDataSource</strong> would use the values input by the user to make the changes. It could use optimistic concurrency to compare all the entered values.</p>
<p>The problem is, I don&#8217;t always display all fields from a particular row on the form, so how would the <strong>LinqDataSource</strong> know what the missing fields were. Remember, all the fields involved in the update are required for the optimistic concurrency to work. That is usually all the fields in a row, and they aren&#8217;t usually all displayed.</p>
<p>So, have a guess. Where does the <strong>LinqDataSource</strong> store it&#8217;s values?</p>
<p>Let&#8217;s think now. Where would be the <em>easiest </em>place to keep it? To keep it really simple, I&#8217;ll let you ignore <a href="http://richardbushnell.net/index.php/2007/12/23/qualities-of-a-dot-net-application-design/">all other aspects of building an application</a>, like security or performance.</p>
<p>Yep, you guessed it &#8211; <strong>ViewState</strong>.</p>
<p>The ViewState actually contains all values for all the fields in a LINQ-to-SQL entity by default. Those values are sent to the client, even if the user isn&#8217;t supposed to be able to see them.</p>
<p>Aaaarrgghhhh!</p>
<p>Now, let&#8217;s not get overexcited. The ViewState is encoded, so it&#8217;s not easy to just go and change it. But it&#8217;s not impossible. In general, I don&#8217;t think it&#8217;s such a great idea to have all data sent to a client by default. Someone is going to overlook something one day, and there&#8217;ll be a costly mistake.</p>
<p>And what if you display a large grid using the LinqDataSource. Well, you aren&#8217;t just getting the ViewState from the grid sent back and forth with your page, but the LinqDataSource is going to store <em>all your data</em> retrieved in the ViewState too.</p>
<p>Bummer!</p>
<p>Great control. Large overhead.</p>
<h2>Kicking out the ViewState</h2>
<p>The good news is that the ASP.Net team realized that this was a problem and did something about it.</p>
<p>If you look carefully, you will notice that the <strong>LinqDataSource</strong> has a property <strong>StoreOriginalValuesInViewState</strong>. By default (sigh) that property is set to true. If you set it to false, the control won&#8217;t work any more. Simple as that.</p>
<p>Here&#8217;s what the official documentation has to say about that:</p>
<blockquote><p>If you set the <strong>StoreOriginalValuesInViewState</strong> property to false, the original values are not persisted in view state for the data-bound control. In that case, LINQ to SQL cannot verify the integrity of the data. LINQ to SQL will throw an exception that indicates a data conflict even if the data in the data source has not actually changed.</p></blockquote>
<p>That&#8217;s in the remarks section of the <strong>LinqDataSource</strong>.<strong>StoreOriginalValuesInViewState</strong> property documentation.</p>
<p>Funnily enough, the same section states the problem with stuffing data into the ViewState:</p>
<blockquote><p>Storing the original values in view state can cause the page size to become unnecessarily large and can expose sensitive data to a malicious user.</p></blockquote>
<p>Now, I don&#8217;t know about you, but that looks like a pretty serious warning to me. Why isn&#8217;t it in a more obvious place, like as a comment that pops in up Intellisense whenever you use a LinqDataSource?</p>
<h2>Check the UpdateCheck</h2>
<p>So how do you handle it? How can you use the <strong>LinqDataSource</strong>?</p>
<p>The answer lies in the generation of the LINQ-to-SQL model which you generate. Each entity field has a <strong>Column </strong>attribute which allows you to specify if it is used for checking during an optimistic concurrency field comparison.</p>
<p>For example, you could create a Model with the following Property:</p>
<pre class="code">[<span style="color: #2b91af">Column</span>(Storage=<span style="color: #a31515">"_AddressID"</span>, UpdateCheck=<span style="color: #2b91af">UpdateCheck</span>.Never, ...
<span style="color: blue">public int </span>AddressID
...</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Notice the <strong>UpdateCheck.Never </strong>value. That means that the field will not be used in the optimistic concurrency check.</p>
<p>The documentation helps a little again:</p>
<blockquote><p>By default, when update and delete operations have been enabled, the <a href="ms-help://ms.vscc.v90/9b2f476d-7f28-2aa8-8143-3082edcf11d5.htm">LinqDataSource</a> control stores the original values for all the records in view state. The <a href="ms-help://ms.vscc.v90/9b2f476d-7f28-2aa8-8143-3082edcf11d5.htm">LinqDataSource</a> control stores values for all primary keys and all properties not marked with UpdateCheck.Never in the Column attribute. You set the UpdateCheck property of the Column attribute in the O/R Designer.</p></blockquote>
<p>Admittedly, I haven&#8217;t yet tried that, so I don&#8217;t really know how if you can change that setting for a field without changing generated code, which would be a big no-no. I&#8217;ll just have to get back to you on that.</p>
<h2>Stamp In, Please</h2>
<p>However, there is a shortcut trick.</p>
<p>Basically, if you add a field of type <strong>timestamp</strong> to your record, only that field will be used for the concurrency check, and only that field&#8217;s data will be stored in the ViewState.</p>
<blockquote><p>If the underlying data source contains a timestamp field that is automatically updated during an update, you can store only that value in view state. In that case, the timestamp property in the entity class is set to IsVersion=true and all the properties are set to UpdateCheck.Never. Because a timestamp field is automatically updated by the database every time that data in that record changes, LINQ to SQL determines from that value if data has changed. This helps reduce the size of view state, and no sensitive data is exposed. LINQ to SQL will check for data consistency by comparing the timestamp value in view state with the timestamp value in the database.</p></blockquote>
<p>The documentation is great, if you know where to find it. <img src='http://www.richardbushnell.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h2>Conclusion</h2>
<p>So, the answer is, if you use the <strong>LinqDataSource</strong> to throw a quick application together, make sure you use a <strong>timestamp</strong> field in your table. Call it <strong>UpdatedOn</strong>, or something. It will make the use of the <strong>LinqDataSource</strong> a lot easier, if only because you&#8217;ll sleep better not worrying about it.</p>

<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F02%2F21%2Fthe-linqdatasource-and-the-hidden-viewstate%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
]]></content:encoded>
			<wfw:commentRss>http://www.richardbushnell.net/2008/02/21/the-linqdatasource-and-the-hidden-viewstate/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>How to Update Data with LINQ-to-SQL</title>
		<link>http://www.richardbushnell.net/2008/02/18/how-to-update-data-with-linq-to-sql/</link>
		<comments>http://www.richardbushnell.net/2008/02/18/how-to-update-data-with-linq-to-sql/#comments</comments>
		<pubDate>Mon, 18 Feb 2008 17:50:38 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[LINQ to SQL]]></category>

		<guid isPermaLink="false">http://richardbushnell.net/index.php/2008/02/18/how-to-update-data-with-linq-to-sql/</guid>
		<description><![CDATA[When learning LINQ-to-SQL, it&#8217;s not immediately obvious how to do an update. Querying is easy, and there are methods for inserting and deleting. Updating usually occurs by modifying an object already known to the DataContext and then calling SubmitChanges on the context. var product = (from p in dataContext.Products where p.ProductID == 1 select p).Single(); [...]]]></description>
			<content:encoded><![CDATA[
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F02%2F18%2Fhow-to-update-data-with-linq-to-sql%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<br><p>When learning LINQ-to-SQL, it&#8217;s not immediately obvious how to do an update. Querying is easy, and there are methods for inserting and deleting. Updating usually occurs by modifying an object already known to the <strong>DataContext</strong> and then calling <strong>SubmitChanges</strong> on the context.</p>
<blockquote><pre class="code"><span style="color: blue">var </span>product = (<span style="color: blue">from </span>p <span style="color: blue">in </span>dataContext.Products
               <span style="color: blue">where </span>p.ProductID == 1
               <span style="color: blue">select </span>p).Single();

product.Name = <span style="color: #a31515">&quot;Richard's product&quot;</span>;

dataContext.SubmitChanges();</pre>
</blockquote>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>It&#8217;s nice to see that MSDN documentation actually addresses the obvious arising question:</p>
<blockquote>
<p>Q. Can I update table data without first querying the database?</p>
<p>A. Although LINQ to SQL does not have set-based update commands, you can use either of the following techniques to update without first querying:</p>
<ul>
<li>Use ExecuteCommand to send SQL code. </li>
<li>Create a new instance of the object and initialize all the current values (fields) that affect the update. Then attach the object to the DataContext by using Attach and modify the field you want to change. </li>
</ul>
</blockquote>
<p><span id="more-54"></span></p>
<p>If you ask me, using an <strong>ExecuteCommand </strong>defeats the object of LINQ-to-SQL. After all, we&#8217;re using it as a data-access-layer to generate entities in code based on the data schema. The last thing we want to have to do is start writing strings of SQL.</p>
<p>So that&#8217;s out.</p>
<h3>I&#8217;m So Attached</h3>
<p>The second option is to use the <strong>Attach</strong> method on the table we&#8217;re updating. I&#8217;ve tried to use the <strong>Attach </strong>method before, but it didn&#8217;t work.</p>
<p>To see what I mean, try this in LINQPad (using the AdventureWorks database from CodePlex):</p>
<blockquote>
<pre class="code"><span style="color: blue">var </span><span style="color: black">product = </span><span style="color: blue">new </span><span style="color: black">Product();
product.ProductID = </span><span style="color: #c81efa">1</span><span style="color: black">;
product.Name = </span><span style="color: #dc1414">&quot;Richard's product&quot;</span><span style="color: black">;

Products.Attach(product);

</span><span style="color: blue">var </span><span style="color: black">changeSet = GetChangeSet();

changeSet.Dump();</span></pre>
</blockquote>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>You&#8217;ll see that there are no changes to make, so no updates are made.</p>
<p>Now, move the line of code that does the update after the call to <strong>Attach</strong>, so as to attach the product first before updating the field:</p>
<blockquote>
<pre class="code"><span style="color: blue">var </span><span style="color: black">product = </span><span style="color: blue">new </span><span style="color: black">Product();
product.ProductID = </span><span style="color: #c81efa">1</span><span style="color: black">;

Products.Attach(product);
</span><span style="color: black">
//Notice we're doing this laterproduct.Name = </span><span style="color: #dc1414">&quot;Richard's product&quot;</span><span style="color: black">;

</span><span style="color: blue">var </span><span style="color: black">changeSet = GetChangeSet();

changeSet.Dump();</span></pre>
</blockquote>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>The c<strong>hangeset</strong> now shows that one update is ready to be made. Unfortunately, if you call <strong>SubmitChanges</strong>, you get an exception:</p>
<blockquote>
<pre class="code">SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.</pre>
</blockquote>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>The MSDN documentation isn&#8217;t so clear here. What do we need to set to get it to work?</p>
<p>The SQL being sent to the database is instructive:</p>
<blockquote>
<pre class="code"><span style="color: blue">UPDATE </span>[Production]<span style="color: gray">.</span>[Product]
<span style="color: blue">SET </span>[Name] <span style="color: gray">= </span>@p9
<span style="color: blue">WHERE </span><span style="color: gray">(</span>[ProductID] <span style="color: gray">= </span>@p0<span style="color: gray">) AND (</span>[Name] <span style="color: gray">IS NULL)
AND (</span>[ProductNumber] <span style="color: gray">IS NULL)
AND (NOT (</span>[MakeFlag] <span style="color: gray">= </span>1<span style="color: gray">))
AND (NOT (</span>[FinishedGoodsFlag] <span style="color: gray">= </span>1<span style="color: gray">))
AND (</span>[Color] <span style="color: gray">IS NULL)
AND (</span>[SafetyStockLevel] <span style="color: gray">= </span>@p1<span style="color: gray">)
AND (</span>[ReorderPoint] <span style="color: gray">= </span>@p2<span style="color: gray">)
AND (</span>[StandardCost] <span style="color: gray">= </span>@p3<span style="color: gray">)
AND (</span>[ListPrice] <span style="color: gray">= </span>@p4<span style="color: gray">)
AND (</span>[Size] <span style="color: gray">IS NULL)
AND (</span>[SizeUnitMeasureCode] <span style="color: gray">IS NULL)
AND (</span>[WeightUnitMeasureCode] <span style="color: gray">IS NULL)
AND (</span>[Weight] <span style="color: gray">IS NULL)
AND (</span>[DaysToManufacture] <span style="color: gray">= </span>@p5<span style="color: gray">)
AND (</span>[ProductLine] <span style="color: gray">IS NULL)
AND (</span>[Class] <span style="color: gray">IS NULL)
AND (</span>[Style] <span style="color: gray">IS NULL)
AND (</span>[ProductSubcategoryID] <span style="color: gray">IS NULL)
AND (</span>[ProductModelID] <span style="color: gray">IS NULL)
AND (</span>[SellStartDate] <span style="color: gray">= </span>@p6<span style="color: gray">)
AND (</span>[SellEndDate] <span style="color: gray">IS NULL)
AND (</span>[DiscontinuedDate] <span style="color: gray">IS NULL)
AND (</span>[rowguid] <span style="color: gray">= </span>@p7<span style="color: gray">)
AND (</span>[ModifiedDate] <span style="color: gray">= </span>@p8<span style="color: gray">)
</span><span style="color: green">-- @p0: Input Int (Size = 0; Prec = 0; Scale = 0) [1]
-- @p1: Input SmallInt (Size = 0; Prec = 0; Scale = 0) [0]
-- @p2: Input SmallInt (Size = 0; Prec = 0; Scale = 0) [0]
-- @p3: Input Decimal (Size = 0; Prec = 29; Scale = 4) [0]
-- @p4: Input Decimal (Size = 0; Prec = 29; Scale = 4) [0]
-- @p5: Input Int (Size = 0; Prec = 0; Scale = 0) [0]</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
</blockquote>
<p>The problem is now that LINQ-to-SQL tables automatically use optimistic concurrency, and for some reason (maybe only in LINQPad) the SellStartDate is not set, and neither are the rowguid or ModifiedDate fields. In any case, either we have to turn off optimistic concurrency, or set all the field values ourselves.</p>
<h3>Using Optimistic Concurrency with Updates</h3>
<p>Unfortunately, by default all fields are used for optimistic concurrency, so you have to set values for all fields. If you were using ASP.Net you could keep a copy of the variables in the session state or something, but at least it saves you a round trip to the database.</p>
<p>Here&#8217;s the code that actually does perform an update:</p>
<blockquote>
<pre class="code"><span style="color: blue">var </span>product = <span style="color: blue">new </span><span style="color: #2b91af">Product</span>();
product.ProductID = 1;
product.Name = <span style="color: #a31515">&quot;Adjustable Race&quot;</span>;
product.ProductNumber = <span style="color: #a31515">&quot;AR-5381&quot;</span>;
product.MakeFlag = <span style="color: blue">false</span>;
product.FinishedGoodsFlag = <span style="color: blue">false</span>;
product.Color = <span style="color: blue">null</span>;
product.SafetyStockLevel = 1000;
product.ReorderPoint = 750;
product.StandardCost = 0.0000M;
product.ListPrice = 0.0000M;
product.Size = <span style="color: blue">null</span>;
product.SizeUnitMeasureCode = <span style="color: blue">null</span>;
product.WeightUnitMeasureCode = <span style="color: blue">null</span>;
product.Weight = <span style="color: blue">null</span>;
product.DaysToManufacture = 0;
product.ProductLine = <span style="color: blue">null</span>;
product.Class = <span style="color: blue">null</span>;
product.Style = <span style="color: blue">null</span>;
product.ProductSubcategoryID = <span style="color: blue">null</span>;
product.ProductModelID = <span style="color: blue">null</span>;
product.SellStartDate = <span style="color: #2b91af">DateTime</span>.Parse(<span style="color: #a31515">&quot;6/1/1998 12:00:00 AM&quot;</span>);
product.SellEndDate = <span style="color: blue">null</span>;
product.DiscontinuedDate = <span style="color: blue">null</span>;
product.Rowguid = <span style="color: blue">new </span><span style="color: #2b91af">Guid</span>(<span style="color: #a31515">&quot;694215b7-08f7-4c0d-acb1-d734ba44c0c8&quot;</span>);
product.ModifiedDate = <span style="color: #2b91af">DateTime</span>.Parse(<span style="color: #a31515">&quot;3/11/2004 10:01:36.827 AM&quot;</span>);

Products.Attach(product);

// Make the change here
product.Name = <span style="color: #a31515">&quot;Richard's product&quot;</span>;

SubmitChanges();</pre>
</blockquote>
<p>So you can avoid two trips to the database by doing the update manually and using the <strong>Attach </strong>method on the table you are updating.</p>
<p>Mind you, I&#8217;m not sure that&#8217;s worth it.</p>
<div style="float:right;margin:0 20px 20px 0">
<iframe style="width: 120px; height: 240px" marginwidth="0" marginheight="0" src="http://rcm.amazon.com/e/cm?t=netsmoo-20&amp;o=1&amp;p=8&amp;l=as1&amp;asins=1590597893&amp;fc1=000000&amp;IS2=1&amp;lt1=_blank&amp;lc1=109DD0&amp;bc1=000000&amp;bg1=FFFFFF&amp;f=ifr" frameborder="0" scrolling="no"></iframe>
</div>
<p>If you want to know more about updating LINQ-to-SQL objects with the DataContext, I recommend <a href="http://www.amazon.com/gp/product/1590597893?ie=UTF8&amp;tag=netsmoo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=1590597893">Pro LINQ: Language Integrated Query in C# 2008</a><img style="margin: 0px; width: 1px; border-top-style: none! important; border-right-style: none! important; border-left-style: none! important; border-bottom-style: none! important" height="1" alt="" src="http://www.assoc-amazon.com/e/ir?t=netsmoo-20&amp;l=as2&amp;o=1&amp;a=1590597893" width="1" border="0" />. It&#8217;s got 6 chapters just about LINQ-to-SQL, the DataContext, and concurrency issues.</p>
<p>P.S. In case you&#8217;re interested, I generated some of that code in LINQPad using the following code (it doesn&#8217;t work for dates or Guids, before anyone complains):</p>
<p><span style="color: blue">var </span>product = (<span style="color: blue">from </span>p <span style="color: blue">in</span>Products</p>
<p><span style="color: blue">where</span>p.ProductID == 1</p>
<p><span style="color: blue">select</span>p).Single();</p>
<p><span style="color: blue">var </span>fields = <span style="color: blue">from </span>field <span style="color: blue">in</span>product.GetType().GetFields()</p>
<p><span style="color: blue">select new</span>{</p>
<p>Name = field.Name,</p>
<p>Value = field.GetValue(product),</p>
<p>TypeName = field.FieldType.Name };</p>
<p><span style="color: blue">foreach </span>(<span style="color: blue">var </span>field <span style="color: blue">in</span>fields)</p>
<p><span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">&quot;product.{0} = {1};&quot;</span>, field.Name,</p>
<p>field.TypeName == <span style="color: #a31515">&quot;String&quot;</span>? <span style="color: #a31515">&quot;\&quot;&quot;</span>+</p>
<p>field.Value + <span style="color: #a31515">&quot;\&quot;&quot;</span>:</p>
<p>field.Value ?? <span style="color: #a31515">&quot;null&quot;</span>);</p>

<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F02%2F18%2Fhow-to-update-data-with-linq-to-sql%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
]]></content:encoded>
			<wfw:commentRss>http://www.richardbushnell.net/2008/02/18/how-to-update-data-with-linq-to-sql/feed/</wfw:commentRss>
		<slash:comments>33</slash:comments>
		</item>
		<item>
		<title>How to See the SQL Generated by a LINQ to SQL Command</title>
		<link>http://www.richardbushnell.net/2008/02/14/how-to-see-the-sql-generated-by-a-linq-to-sql-command/</link>
		<comments>http://www.richardbushnell.net/2008/02/14/how-to-see-the-sql-generated-by-a-linq-to-sql-command/#comments</comments>
		<pubDate>Thu, 14 Feb 2008 09:11:10 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[LINQ to SQL]]></category>
		<category><![CDATA[Tips]]></category>

		<guid isPermaLink="false">http://richardbushnell.net/index.php/2008/02/14/how-to-see-the-sql-generated-by-a-linq-to-sql-command/</guid>
		<description><![CDATA[Quick tip: If you want to see the SQL generated by LINQ to SQL for a query or command, simply set the Log property of your generated DataContext class to an instance of a TextReader. If this is your code: using System; using System.Linq; using System.Data.Linq; namespace LINQtoSQLConsole { class Program { static void Main(string[] [...]]]></description>
			<content:encoded><![CDATA[
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F02%2F14%2Fhow-to-see-the-sql-generated-by-a-linq-to-sql-command%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<br><p>Quick tip: If you want to see the SQL generated by LINQ to SQL for a query or command, simply set the Log property of your generated DataContext class to an instance of a TextReader.</p>
<p>If this is your code:</p>
<pre class="code"><span style="color: blue">using </span>System;
<span style="color: blue">using </span>System.Linq;
<span style="color: blue">using </span>System.Data.Linq;

<span style="color: blue">namespace </span>LINQtoSQLConsole {
  <span style="color: blue">class </span><span style="color: #2b91af">Program </span>{
    <span style="color: blue">static void </span>Main(<span style="color: blue">string</span>[] args) {

      <span style="color: blue">var </span>db = <span style="color: blue">new </span><span style="color: #2b91af">NorthwindDataContext</span>();

      <span style="color: green">// Use the console to see the SQL
      </span>db.Log = <span style="color: #2b91af">Console</span>.Out;

      <span style="color: green">// A query
      </span><span style="color: blue">var </span>cust = db.Customers.Single(
                    c =&gt; c.CustomerID == <span style="color: #a31515">"ALFKI"</span>);

      <span style="color: green">// An update
      </span>cust.Region = <span style="color: #a31515">"Northwest"</span>;
      db.SubmitChanges();
    }
  }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p>&#8230; then this is what you&#8217;ll see:</p>
<p><a href="http://www.richardbushnell.net/wp-content/uploads/2008/02/image.png"><img border="0" width="244" src="http://www.richardbushnell.net/wp-content/uploads/2008/02/image-thumb.png" alt="image" height="134" style="border-width: 0px" /></a></p>
<p>Pretty good, eh?</p>

<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F02%2F14%2Fhow-to-see-the-sql-generated-by-a-linq-to-sql-command%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
]]></content:encoded>
			<wfw:commentRss>http://www.richardbushnell.net/2008/02/14/how-to-see-the-sql-generated-by-a-linq-to-sql-command/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to Use Grouping in C# LINQ Syntax</title>
		<link>http://www.richardbushnell.net/2008/02/08/how-to-use-grouping-in-c-linq-syntax/</link>
		<comments>http://www.richardbushnell.net/2008/02/08/how-to-use-grouping-in-c-linq-syntax/#comments</comments>
		<pubDate>Fri, 08 Feb 2008 21:22:54 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[IGrouping]]></category>

		<guid isPermaLink="false">http://richardbushnell.net/index.php/2008/02/08/how-to-use-grouping-in-c-linq-syntax/</guid>
		<description><![CDATA[When you started using LINQ, did you think it looked like SQL? I did. The more I learned LINQ, the more I realized it wasn&#8217;t anything like SQL. Take grouping, for example. Because LINQ has a group by statement, and it looks like SQL, I assumed that the syntax for grouping in LINQ would be [...]]]></description>
			<content:encoded><![CDATA[
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F02%2F08%2Fhow-to-use-grouping-in-c-linq-syntax%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<br><p>When you started using LINQ, did you think it looked like SQL? I did.</p>
<p>The more I learned LINQ, the more I realized it <em>wasn&#8217;t anything like</em> SQL. Take grouping, for example. Because LINQ has a <span style="color: blue">group by </span>statement, and it looks like SQL, I assumed that the syntax for grouping in LINQ would be just like SQL. Ha ha! Wrong! As soon as I tried to use it, I discovered that the LINQ syntax is not only nothing like the SQL equivalent, but the whole grouping concept in LINQ is completely different too.</p>
<p>At first glance, the two syntaxes look <em>slightly </em>similar.</p>
<p>SQL:</p>
<pre class="code"><span style="color: blue">select </span>ReportsTo<span style="color: gray">, </span><span style="color: magenta">count</span><span style="color: gray">(</span>LastName<span style="color: gray">) </span><span style="color: blue">as </span>NameCount
<span style="color: blue">from </span>Employees
<span style="color: blue">group by </span>ReportsTo</pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p>LINQ (C#):</p>
<pre class="code"><span style="color: blue">from </span>employee <span style="color: blue">in </span>Employees
<span style="color: blue">group </span>employee <span style="color: blue">by </span>employee.ReportsTo</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Ignoring the omission of the select statement from LINQ, and the requirement of a range variable, they do look similar. But looks can be deceiving.</p>
<p>Let me explain why.</p>
<p><span id="more-48"></span></p>
<h2>Grouping in SQL</h2>
<p>In SQL, you typically group a set of entities using the following syntax:</p>
<pre class="code"><span style="color: blue">select </span>ReportsTo<span style="color: gray">, </span><span style="color: magenta">count</span><span style="color: gray">(</span>LastName<span style="color: gray">) </span><span style="color: blue">as </span>NameCount
<span style="color: blue">from </span>Employees
<span style="color: blue">group by </span>ReportsTo</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>This kind of query results in a simple table with two columns: ReportsTo and NameCount. The count of the names was grouped into a single column using an aggregate function.</p>
<p>Of course, this is a simple example; you could do much more complex grouping by using more expressions in the aggregation or the group by statement. Whatever the grouping though, the result is a flat table.</p>
<p>LINQ is different. Completely different.</p>
<h2>Grouping in LINQ</h2>
<p>Before you can understand the LINQ syntax, you have to understand how grouping works in LINQ.</p>
<p>When you use the <span style="color: blue">group by </span>statement, the C# compiler translates it to the LINQ Enumerable&#8217;s GroupBy extension method. The GroupBy method returns an object of type</p>
<pre class="code"><span style="color: #2b91af">  IEnumerable</span>&lt;<span style="color: #2b91af">IGrouping</span>&lt;TKey, TSource&gt;&gt;</pre>
<p>The GroupBy method takes a parameter of a delegate which specifies the key of each grouping. The key is defined to be of type TKey, and is usually inferred by the compiler depending on the expression.</p>
<p>The key to understanding the C# query syntax is that you <em>don&#8217;t</em> get back a <em>flat</em> structure from <span style="color: blue">group by</span>, as you would with SQL. You actually get an &#8220;IEnumerable&#8221; of &#8220;IGrouping&#8221; objects.</p>
<p>The IGrouping interface has only one property, &#8220;Key&#8221;, and implements IEnumerable&lt;TElement&gt;. Again, TElement is usually inferred. &#8220;Key&#8221; is typed as the generic type you define for TKey. For the minute, that&#8217;s not so important, so we&#8217;ll come back to the Key later.</p>
<p>One of the first indications that LINQ is different to SQL is that you discover it is possible to finish a LINQ statement with a <span style="color: blue">group by </span>statement without needing a Select. As IGrouping implements IEnumerable, <span style="color: blue">group by </span>actually returns an IEnumerable of IEnumerable. The result is a set of sets. It&#8217;s <em>not</em> a flat table. To use it, you have to iterate over it again or perform another operation on the set.</p>
<p>Let&#8217;s see if an example can make it clearer.</p>
<p>When grouping a set of employees, you might use the following code:</p>
<pre class="code"><span style="color: blue">var </span>emp1 = <span style="color: blue">new </span>{ ReportsTo = 1, LastName = <span style="color: #a31515">"Richard" </span>};
<span style="color: blue">var </span>emp2 = <span style="color: blue">new </span>{ ReportsTo = 1, LastName = <span style="color: #a31515">"Christopher" </span>};
<span style="color: blue">var </span>emp3 = <span style="color: blue">new </span>{ ReportsTo = 2, LastName = <span style="color: #a31515">"John" </span>};
<span style="color: blue">var </span>emp4 = <span style="color: blue">new </span>{ ReportsTo = 2, LastName = <span style="color: #a31515">"Greg" </span>};
<span style="color: blue">var </span>employees = <span style="color: blue">new</span>[] { emp1, emp2, emp3, emp4 };

<span style="color: blue">var </span>groups =
<span style="color: blue">  from </span>employee <span style="color: blue">in </span>employees
<span style="color: blue">  group </span>employee <span style="color: blue">by </span>employee.ReportsTo;

<span style="color: blue">foreach </span>(<span style="color: blue">var </span>group <span style="color: blue">in </span>groups)
  <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"{0} employees report to {1}."</span>,
    group.Key, group.Count());</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>(Don&#8217;t worry about the anonymous class definitions for now. You just have to know that my employee objects are all treated as the same type internally, so this is valid C# code.)</p>
<p>The employees variable is of type IEnumerable, so it can be used in a LINQ statement. The groups variable is also an IEnumerable, as it is a set of results, as usually returned by a LINQ statement. Remember though, <em>it&#8217;s not like </em>the set you would get back in a SQL statement. It is actually an IEnumerable of IGrouping, or an IEnumerable of IEnumerable.</p>
<p>To do something with the grouping, you have to either treat it as another IEnumerable, and iterate over it, or use methods like Count() to do something with it.</p>
<pre class="code"><span style="color: blue">foreach </span><span style="color: black">(</span><span style="color: blue">var <span style="color: black">group </span>in </span><span style="color: black">groups)
  </span><span style="color: blue">foreach </span><span style="color: black">(</span><span style="color: blue">var </span><span style="color: black">employee </span><span style="color: blue">in <span style="color: black">group</span></span><span style="color: black">)
    Console.WriteLine(</span><span style="color: #dc1414">"{0} reports to {1}"</span><span style="color: black">,
      employee.LastName, employee.ReportsTo);</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>This is how LINQPad shows what is contained in the groups variable:</p>
<table class="MsoNormalTable" style="border: medium none ; margin-left: 1.2pt; border-collapse: collapse" border="1" cellpadding="0" cellspacing="0">
<tr>
<td style="border: 1pt solid #aaaaaa; padding: 0cm 2.4pt 1.2pt 1.2pt; background: #1177bb none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><strong><span style="font-size: 8.5pt; color: white; font-family: 'Tahoma','sans-serif'"><span><u><span>IEnumerable&lt;IGrouping&lt;Int32,&gt;&gt;</span></u></span> </span></strong></p>
</td>
</tr>
<tr>
<td style="border-style: none solid solid; border-color: -moz-use-text-color rgb(170, 170, 170) rgb(170, 170, 170); border-width: medium 1pt 1pt; padding: 1.2pt 2.4pt" valign="top">
<table class="MsoNormalTable" style="border-collapse: collapse" border="0" cellpadding="0" cellspacing="0">
<tr>
<td style="padding: 0cm 1.2pt" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><em><span style="font-size: 9.5pt; color: green; font-family: 'Verdana','sans-serif'">Key=</span></em><span style="font-size: 9.5pt; font-family: 'Verdana','sans-serif'"> </span></p>
</td>
<td style="padding: 0cm 1.2pt" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><span style="font-size: 9.5pt; font-family: 'Verdana','sans-serif'">1 </span></p>
</td>
</tr>
</table>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal">&nbsp;</p>
<table class="MsoNormalTable" style="border: medium none ; margin-left: 1.2pt; border-collapse: collapse" border="1" cellpadding="0" cellspacing="0">
<tr>
<td style="border: 1pt solid #aaaaaa; padding: 0cm 2.4pt 1.2pt 1.2pt; background: #1177bb none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial" colspan="2" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><strong><span style="font-size: 8.5pt; color: white; font-family: 'Tahoma','sans-serif'"><span><u><span>IGrouping&lt;Int32,&gt; (2 items)</span></u></span> </span></strong></p>
</td>
</tr>
<tr>
<td style="border-style: none solid solid; border-color: -moz-use-text-color rgb(119, 119, 119) rgb(119, 119, 119); border-width: medium 1pt 1pt; padding: 1.2pt 2.4pt; background: #dddddd none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><strong><span style="font-size: 8.5pt; font-family: 'Tahoma','sans-serif'">ReportsTo </span></strong></p>
</td>
<td style="border-style: none solid solid none; border-color: -moz-use-text-color rgb(119, 119, 119) rgb(119, 119, 119) -moz-use-text-color; border-width: medium 1pt 1pt medium; padding: 1.2pt 2.4pt; background: #dddddd none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><strong><span style="font-size: 8.5pt; font-family: 'Tahoma','sans-serif'">LastName </span></strong></p>
</td>
</tr>
<tr>
<td style="border-style: none solid solid; border-color: -moz-use-text-color rgb(170, 170, 170) rgb(170, 170, 170); border-width: medium 1pt 1pt; padding: 1.2pt 2.4pt" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><span style="font-size: 9.5pt; font-family: 'Verdana','sans-serif'">1 </span></p>
</td>
<td style="border-style: none solid solid none; border-color: -moz-use-text-color rgb(170, 170, 170) rgb(170, 170, 170) -moz-use-text-color; border-width: medium 1pt 1pt medium; padding: 1.2pt 2.4pt" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><span style="font-size: 9.5pt; font-family: 'Verdana','sans-serif'">Richard </span></p>
</td>
</tr>
<tr>
<td style="border-style: none solid solid; border-color: -moz-use-text-color rgb(170, 170, 170) rgb(170, 170, 170); border-width: medium 1pt 1pt; padding: 1.2pt 2.4pt" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><span style="font-size: 9.5pt; font-family: 'Verdana','sans-serif'">1 </span></p>
</td>
<td style="border-style: none solid solid none; border-color: -moz-use-text-color rgb(170, 170, 170) rgb(170, 170, 170) -moz-use-text-color; border-width: medium 1pt 1pt medium; padding: 1.2pt 2.4pt" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><span style="font-size: 9.5pt; font-family: 'Verdana','sans-serif'">Christopher </span></p>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td style="border-style: none solid solid; border-color: -moz-use-text-color rgb(170, 170, 170) rgb(170, 170, 170); border-width: medium 1pt 1pt; padding: 1.2pt 2.4pt" valign="top">
<table class="MsoNormalTable" style="border-collapse: collapse" border="0" cellpadding="0" cellspacing="0">
<tr>
<td style="padding: 0cm 1.2pt" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><em><span style="font-size: 9.5pt; color: green; font-family: 'Verdana','sans-serif'">Key=</span></em><span style="font-size: 9.5pt; font-family: 'Verdana','sans-serif'"> </span></p>
</td>
<td style="padding: 0cm 1.2pt" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><span style="font-size: 9.5pt; font-family: 'Verdana','sans-serif'">2 </span></p>
</td>
</tr>
</table>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><span style="display: none; font-size: 9.5pt; font-family: 'Verdana','sans-serif'"></span></p>
<table class="MsoNormalTable" style="border: medium none ; margin-left: 1.2pt; border-collapse: collapse" border="1" cellpadding="0" cellspacing="0">
<tr>
<td style="border: 1pt solid #aaaaaa; padding: 0cm 2.4pt 1.2pt 1.2pt; background: #1177bb none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial" colspan="2" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><strong><span style="font-size: 8.5pt; color: white; font-family: 'Tahoma','sans-serif'"><span><u><span>IGrouping&lt;Int32,&gt; (2 items)</span></u></span> </span></strong></p>
</td>
</tr>
<tr>
<td style="border-style: none solid solid; border-color: -moz-use-text-color rgb(119, 119, 119) rgb(119, 119, 119); border-width: medium 1pt 1pt; padding: 1.2pt 2.4pt; background: #dddddd none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><strong><span style="font-size: 8.5pt; font-family: 'Tahoma','sans-serif'">ReportsTo </span></strong></p>
</td>
<td style="border-style: none solid solid none; border-color: -moz-use-text-color rgb(119, 119, 119) rgb(119, 119, 119) -moz-use-text-color; border-width: medium 1pt 1pt medium; padding: 1.2pt 2.4pt; background: #dddddd none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><strong><span style="font-size: 8.5pt; font-family: 'Tahoma','sans-serif'">LastName </span></strong></p>
</td>
</tr>
<tr>
<td style="border-style: none solid solid; border-color: -moz-use-text-color rgb(170, 170, 170) rgb(170, 170, 170); border-width: medium 1pt 1pt; padding: 1.2pt 2.4pt" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><span style="font-size: 9.5pt; font-family: 'Verdana','sans-serif'">2 </span></p>
</td>
<td style="border-style: none solid solid none; border-color: -moz-use-text-color rgb(170, 170, 170) rgb(170, 170, 170) -moz-use-text-color; border-width: medium 1pt 1pt medium; padding: 1.2pt 2.4pt" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><span style="font-size: 9.5pt; font-family: 'Verdana','sans-serif'">John </span></p>
</td>
</tr>
<tr>
<td style="border-style: none solid solid; border-color: -moz-use-text-color rgb(170, 170, 170) rgb(170, 170, 170); border-width: medium 1pt 1pt; padding: 1.2pt 2.4pt" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><span style="font-size: 9.5pt; font-family: 'Verdana','sans-serif'">2 </span></p>
</td>
<td style="border-style: none solid solid none; border-color: -moz-use-text-color rgb(170, 170, 170) rgb(170, 170, 170) -moz-use-text-color; border-width: medium 1pt 1pt medium; padding: 1.2pt 2.4pt" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><span style="font-size: 9.5pt; font-family: 'Verdana','sans-serif'">Greg </span></p>
</td>
</tr>
</table>
</td>
</tr>
</table>
<p>Notice that each IGrouping has an associated Key property of type Int32.</p>
<h2>Grouping Syntax in LINQ</h2>
<p class="MsoNormal">So now it should be a little easier to understand how to use the LINQ <span style="color: blue">group by</span> statement.</p>
<p class="MsoNormal">In LINQ, you always need to <strong>declare the range variable </strong>between <span style="color: blue">group</span> and <span style="color: blue">by</span>.</p>
<p class="MsoNormal"><font size="2"><font face="Courier New"><span style="color: blue">from </span>employee <span style="color: blue">in </span>Employees </font></font></p>
<p><span style="color: blue"><font size="2"><font face="Courier New">group </font></font></span><font size="2"><font face="Courier New">employee <span style="color: blue">by </span>employee.ReportsTo</font></font></p>
<p class="MsoNormal">After <span style="color: blue">by</span>, you give an expression which returns the value for the <span style="color: blue">Key</span>. The enumeration is then split into groups of <span style="color: blue">IGroupings </span>where the key for each item in that <span style="color: blue">IGrouping</span> is the same.</p>
<p class="MsoNormal">So here, we specify the employee.ReportsTo variable as the key. Each employee with a different value for ReportsTo creates a new <span style="color: blue">IGrouping</span> with a <span style="color: blue">Key</span> of that value. The employee is then added to that new <span style="color: blue">IGrouping</span> as an item. The <span style="color: blue">IGrouping</span> is then added to the returned <span style="color: blue">IEnumerable&lt;<span style="color: blue">IGrouping&lt;&gt;<strong>&gt;</strong></span></span>.</p>
<p class="MsoNormal">The next time an item in the employees variable has the same value for ReportsTo as the <span style="color: blue">Key</span> property of an already-existing <span style="color: blue">IGrouping</span> object, the item is simply added to that <span style="color: blue">IGrouping</span>.</p>
<p class="MsoNormal">Of course, that&#8217;s probably not the way it works under the covers. But I&#8217;m not trying to specify the algorithm, just what happens in the end result.</p>
<p class="MsoNormal">In the end, an object implementing <span style="color: blue">IEnumerable&lt;<span style="color: blue">IGrouping&lt;&gt;<strong>&gt;</strong></span></span> is returned by the LINQ statement. As each item in the <span style="color: blue">IEnumerable </span>is an <span style="color: blue"><span style="color: blue">IGrouping</span></span>, you can either use it&#8217;s <span style="color: blue">Key</span> or treat it as an <span style="color: blue">IEnumerable</span>.</p>
<p class="MsoNormal">So there you have it. Just remember, group by is nothing like SQL, and it returns an <span style="color: blue">IEnumerable </span>of <span style="color: blue">IGrouping</span>, and you should stay happy.</p>
<p class="MsoNormal">At least until you meet SelectMany&#8230; :=)</p>
<div style="float:left;margin:0 20px 20px 0">
<iframe src="http://rcm.amazon.com/e/cm?t=netsmoo-20&amp;o=1&amp;p=8&amp;l=as1&amp;asins=0596527578&amp;fc1=000000&amp;IS2=1&amp;lt1=_blank&amp;lc1=2586B3&amp;bc1=000000&amp;bg1=FFFFFF&amp;f=ifr" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
</div>
<p>If you want to learn more about grouping in LINQ, take a look at chapter 9 of the excellent <a href="http://www.amazon.com/gp/product/0596527578?ie=UTF8&amp;tag=netsmoo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0596527578">C# 3.0 in a Nutshell: A Desktop Quick Reference (In a Nutshell (O&#8217;Reilly))</a><img src="http://www.assoc-amazon.com/e/ir?t=netsmoo-20&amp;l=as2&amp;o=1&amp;a=0596527578" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />, by Ben and Joseph Albahari. The chapter has some great explanations and examples. In particular, they have an example of grouping with multiple keys, which I found very interesting.</p>

<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F02%2F08%2Fhow-to-use-grouping-in-c-linq-syntax%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
]]></content:encoded>
			<wfw:commentRss>http://www.richardbushnell.net/2008/02/08/how-to-use-grouping-in-c-linq-syntax/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>LINQ to DataSets &#8211; the Missing Manual</title>
		<link>http://www.richardbushnell.net/2008/02/04/linq-to-datasets-the-missing-manual/</link>
		<comments>http://www.richardbushnell.net/2008/02/04/linq-to-datasets-the-missing-manual/#comments</comments>
		<pubDate>Mon, 04 Feb 2008 09:50:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[books]]></category>
		<category><![CDATA[free]]></category>

		<guid isPermaLink="false">http://richardbushnell.net/index.php/2008/02/04/linq-to-datasets-the-missing-manual/</guid>
		<description><![CDATA[Last week I had to prepare a small presentation for a new LINQ workshop. For my research, I browsed through the MSDN documentation on LINQ where I came across a reference to &#34;LINQ to DataSets&#34;. I couldn&#8217;t find any more information about it though, and so LINQ to DataSets got a small mention in my [...]]]></description>
			<content:encoded><![CDATA[
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F02%2F04%2Flinq-to-datasets-the-missing-manual%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<br><p><a href="http://www.amazon.com/gp/product/1933988169?ie=UTF8&amp;tag=netsmoo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=1933988169"><img style="margin: 0px 20px 20px 0px" src="/images/21bKr5u-oYL._AA_SL160_.jpg" align="left" border="0" /></a><img style="margin: 0px; border-top-style: none! important; border-right-style: none! important; border-left-style: none! important; border-bottom-style: none! important" height="1" alt="" src="http://www.assoc-amazon.com/e/ir?t=netsmoo-20&amp;l=as2&amp;o=1&amp;a=1933988169" width="1" border="0" /></p>
<p>Last week I had to prepare a small presentation for a new LINQ workshop. For my research, I browsed through the MSDN documentation on LINQ where I came across a reference to &quot;LINQ to DataSets&quot;. I couldn&#8217;t find any more information about it though, and so LINQ to DataSets got a small mention in my presentation, but I couldn&#8217;t say anything more about it.</p>
<p>This morning I discovered that <a href="http://weblogs.asp.net/fmarguerie/archive/2008/01/21/linq-in-action-final-pdf-ebook-available.aspx" target="_blank">Fabrice Marguerie</a> and his co-authors have published a bonus <a href="http://www.manning-source.com/books/marguerie/bonusch14.pdf" target="_blank">47-page chapter</a> of their book &quot;<a href="http://www.amazon.com/gp/product/1933988169?ie=UTF8&amp;tag=netsmoo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=1933988169">LINQ in Action</a><img style="margin: 0px; border-top-style: none! important; border-right-style: none! important; border-left-style: none! important; border-bottom-style: none! important" height="1" alt="" src="http://www.assoc-amazon.com/e/ir?t=netsmoo-20&amp;l=as2&amp;o=1&amp;a=1933988169" width="1" border="0" />&quot;, all about this very subject. The chapter is called &quot;Working with LINQ and DataSets&quot;, and they have made a <a href="http://www.manning-source.com/books/marguerie/bonusch14.pdf" target="_blank">PDF version available online</a> for FREE download from the <a href="http://www.manning.com/marguerie/" target="_blank">Manning Press website</a>.</p>
<p>You can <a href="http://www.manning-source.com/books/marguerie/bonusch14.pdf" target="_blank">go get it</a> right now.</p>
<p>Thanks Fabrice, for filling in the missing gap.</p>
<p>I&#8217;m going back to update my presentation&#8230;</p>

<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F02%2F04%2Flinq-to-datasets-the-missing-manual%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
]]></content:encoded>
			<wfw:commentRss>http://www.richardbushnell.net/2008/02/04/linq-to-datasets-the-missing-manual/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Using LinqPad to Create a Time-Selector Drop-Down List</title>
		<link>http://www.richardbushnell.net/2008/01/18/using-linqpad-to-create-a-time-selector-drop-down-list/</link>
		<comments>http://www.richardbushnell.net/2008/01/18/using-linqpad-to-create-a-time-selector-drop-down-list/#comments</comments>
		<pubDate>Fri, 18 Jan 2008 17:47:28 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[LinqPad]]></category>

		<guid isPermaLink="false">http://richardbushnell.net/index.php/2008/01/18/using-linqpad-to-create-a-time-selector-drop-down-list/</guid>
		<description><![CDATA[I am really getting into LINQ now! I think it&#8217;s fantastic. I recently wanted to develop a quick drop-down list in ASP.Net which allows a user to select a time of day from a list. The times are 15 minutes apart, so the list would look like this: &#8230; 08:00 08:15 08:30 08:45 09:00 &#8230; [...]]]></description>
			<content:encoded><![CDATA[
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F01%2F18%2Fusing-linqpad-to-create-a-time-selector-drop-down-list%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<br><p>I am <em>really </em>getting into LINQ now! I think it&#8217;s fantastic. I recently wanted to develop a quick drop-down list in ASP.Net which allows a user to select a time of day from a list. The times are 15 minutes apart, so the list would look like this:</p>
<p>&#8230;<br /> 08:00<br /> 08:15<br /> 08:30<br /> 08:45<br /> 09:00<br /> &#8230;</p>
<p>&#8230; and so on.</p>
<p>Before LINQ, I would have done this with a for loop, like this:</p>
<pre class="code"><span style="color: #2b91af">List</span>&lt;<span style="color: blue">string</span>&gt; times = <span style="color: blue">new </span><span style="color: #2b91af">List</span>&lt;<span style="color: blue">string</span>&gt;();
<span style="color: blue">for </span>(<span style="color: blue">int </span>hour = 0; hour &lt; 24; hour++)
  <span style="color: blue">for </span>(<span style="color: blue">int </span>minute = 0; minute &lt; 60; minute++)
    <span style="color: blue">if </span>(minute % 15 == 0)
       times.Add(<span style="color: blue">string</span>.Format(
         <span style="color: #a31515">"{0:00}:{1:00}"</span>, hour, minute));</pre>
<p>That&#8217;s not difficult, although it&#8217;s not so easy to understand. I would have to write a small console app or test to make sure I had done it correct though.</p>
<p>I thought this might be a good opportunity to use <a href="http://www.linqpad.net" target="_blank">LinqPad</a>. It&#8217;s a great tool. You can use it to test a LINQ statement in a live window, so I thought I&#8217;d give it a go.</p>
<p>First I needed a LINQ statement to test.</p>
<p><span id="more-36"></span></p>
<h2>Designing the LINQ Statement</h2>
<p>The first thing I needed was an integer for the hour. That&#8217;s quite easy, especially if you use the Range Extension Method technique as I wrote about before. That method allows you to create an IEnumerable&lt;int&gt; from a simple statement, like 1.To(10). So to get the hours of the day, I can simply start with:</p>
<pre class="code"><span style="color: blue">from </span><span style="color: black">hour </span><span style="color: blue">in </span><span style="color: #c81efa">0</span><span style="color: black">.To(</span><span style="color: #c81efa">23</span><span style="color: black">)</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Now I need to do a cross-join with the minutes. In C# comprehension syntax, you do that by simply adding another <font color="#0000ff">from</font> statement. At first, I thought I could do it by using an enumeration of minutes, specifying each value I wanted specifically. To do that I wrote this:</p>
<pre class="code"><span style="color: blue">from </span><span style="color: black">hour </span><span style="color: blue">in </span><span style="color: #c81efa">0</span><span style="color: black">.To(</span><span style="color: #c81efa">23</span><span style="color: black">)
</span><span style="color: blue">from </span><span style="color: black">minute </span><span style="color: blue">in new</span><span style="color: black">[] {</span><span style="color: #c81efa">0</span><span style="color: black">, </span><span style="color: #c81efa">15</span><span style="color: black">, </span><span style="color: #c81efa">30</span><span style="color: black">, </span><span style="color: #c81efa">45</span><span style="color: black">}</span></pre>
<p><a href="http://11011.net/software/vspaste"></a>That works very nicely. I think it&#8217;s easy to understand too. Even if you were going to come back to it years from now, you could still easily see what is being done.</p>
<p>Another alternative is to do the same as the <font color="#0000ff">for</font> statement above, go through the numbers 0 to 59, selecting only those which are divisible by 15. You would do that using another range and a filter:</p>
<pre class="code"><span style="color: blue">from </span><span style="color: black">hour </span><span style="color: blue">in </span><span style="color: #c81efa">0</span><span style="color: black">.To(</span><span style="color: #c81efa">23</span><span style="color: black">)
</span><span style="color: blue">from </span><span style="color: black">minute </span><span style="color: blue">in </span><span style="color: #c81efa">0</span><span style="color: black">.To(</span><span style="color: #c81efa">59</span><span style="color: black">)
</span><span style="color: blue">where </span><span style="color: black">minute % </span><span style="color: #c81efa">15 </span><span style="color: black">== </span><span style="color: #c81efa">0</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Again, I like the way this looks. Another developer should have no difficulty reading that.</p>
<p>To select the string, we will also use the same format as before, this time using the <font color="#0000ff">select</font> keyword:</p>
<pre class="code"><span style="color: blue">select string</span><span style="color: black">.Format(</span><span style="color: #dc1414">"{0:00}:{1:00}"</span><span style="color: black">, hour, minute)</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>You then simply assign the value of this statement to a variable, like this:</p>
<pre class="code"><span style="color: blue">var </span>times = <span style="color: blue">from </span>hour <span style="color: blue">in </span>0.To(23)
            <span style="color: blue">from </span>minute <span style="color: blue">in </span>0.To(59)
            <span style="color: blue">where </span>minute % 15 == 0
            <span style="color: blue">select string</span>.Format(<span style="color: #a31515">"{0:00}:{1:00}"</span>, hour, minute);</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<h2>Using LinqPad to Test the Result</h2>
<p>Now, if you haven&#8217;t already, go <a href="http://www.linqpad.net/" target="_blank">download LinqPad from here</a>, and open it up. You will see a window to write a statement in the top right.</p>
<p>Before you continue, you need to add the extension methods to use my &#8220;To()&#8221; method. As a treat, just for you, <a href="http://www.richardbushnell.net/wp-content/uploads/2008/01/richardbushnellextensions.zip" target="_blank">here&#8217;s a simple assembly and a code file</a> you can use straight away. Download it, save the binary dll somewhere, then do the following in LinqPad:</p>
<ol>
<li>From the menu, click &#8220;Query&#8221;, then &#8220;Advanced Properties&#8221; (or press F4).
<li>On the Additional References tab, click the &#8220;Add&#8230;&#8221; button.
<li>Click the &#8220;Browse&#8230;&#8221; button on the window which pops up.
<li>Go to the location you saved RichardBushnell.Extensions.dll to, and select it. You should see it added to the list of additional references.
<li>Change to the Additional Namespace Imports tab.
<li>Type &#8220;RichardBushnell.Extensions&#8221;
<li>Click &#8220;OK&#8221;. </li>
</ol>
<p>Now, put your cursor in the Query1 tab, and paste in the following:</p>
<pre class="code"><span style="color: blue">from </span><span style="color: black">hour </span><span style="color: blue">in </span><span style="color: #c81efa">0</span><span style="color: black">.To(</span><span style="color: #c81efa">23</span><span style="color: black">)
</span><span style="color: blue">from </span><span style="color: black">minute </span><span style="color: blue">in </span><span style="color: #c81efa">0</span><span style="color: black">.To(</span><span style="color: #c81efa">59</span><span style="color: black">)
</span><span style="color: blue">where </span><span style="color: black">minute % </span><span style="color: #c81efa">15 </span><span style="color: black">== </span><span style="color: #c81efa">0
</span><span style="color: blue">select string</span><span style="color: black">.Format(</span><span style="color: #dc1414">"{0:00}:{1:00}"</span><span style="color: black">, hour, minute)</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Press F5, and you will see a generated list like this:</p>
<p><a href="http://www.richardbushnell.net/wp-content/uploads/2008/01/image2.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="176" alt="image" src="http://www.richardbushnell.net/wp-content/uploads/2008/01/image-thumb2.png" width="244" border="0"></a></p>
<p>And that&#8217;s it! You can now see <em>exactly</em> what you will get when you run this code.</p>
<p>What do you think? I&#8217;d love to hear your comments.</p>

<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F01%2F18%2Fusing-linqpad-to-create-a-time-selector-drop-down-list%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
]]></content:encoded>
			<wfw:commentRss>http://www.richardbushnell.net/2008/01/18/using-linqpad-to-create-a-time-selector-drop-down-list/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Using Lambda Expressions with LINQ to SQL</title>
		<link>http://www.richardbushnell.net/2008/01/16/using-lambda-expressions-with-linq-to-sql/</link>
		<comments>http://www.richardbushnell.net/2008/01/16/using-lambda-expressions-with-linq-to-sql/#comments</comments>
		<pubDate>Wed, 16 Jan 2008 13:43:46 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[Software]]></category>

		<guid isPermaLink="false">http://richardbushnell.net/index.php/2008/01/16/using-lambda-expressions-with-linq-to-sql/</guid>
		<description><![CDATA[When using LINQ, you need to be careful to use the right kind of Lambda expression. &#8220;What, there is more than one kind?&#8221;, I hear you gasp. There sure is! And if you aren&#8217;t careful, you&#8217;ll get a nice little message at runtime to tell you: &#8220;System.Object DynamicInvoke(System.Object[])&#8217; has no supported translation to SQL.&#8221; What [...]]]></description>
			<content:encoded><![CDATA[
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F01%2F16%2Fusing-lambda-expressions-with-linq-to-sql%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<br><p>When using LINQ, you need to be careful to use the right kind of Lambda expression. &#8220;What, there is more than one kind?&#8221;, I hear you gasp. There sure is! And if you aren&#8217;t careful, you&#8217;ll get a nice little message at runtime to tell you:</p>
<blockquote><p>&#8220;System.Object DynamicInvoke(System.Object[])&#8217; has no supported translation to SQL.&#8221;</p>
</blockquote>
<p>What that literally means is &#8220;You&#8217;re not using lambdas right, you dummy!&#8221;</p>
<p>Let me explain.</p>
<p><span id="more-31"></span></p>
<h2>A Refactoring Problem</h2>
<p>Let&#8217;s start with my problem. I created a Controller class which uses a DataContext to check for an item in a database, and then, if the item was not found, it inserts one. The class looks like this:</p>
<pre class="code"><span style="color: blue">  public class </span><span style="color: #2b91af">UserController </span>{
    <span style="color: blue">public void </span>CreateIDUser(<span style="color: blue">string </span>ID) {
      <span style="color: blue">var </span>DB = <span style="color: blue">new </span><span style="color: #2b91af">DBataContext</span>();
      <span style="color: blue">var </span>existingUsers = <span style="color: blue">from </span>user <span style="color: blue">in </span>DB.Users
                          <span style="color: blue">where </span>user.ID == ID
                          <span style="color: blue">select </span>user;

      <span style="color: blue">if </span>(existingUsers.Count() == 0) {
        <span style="color: #2b91af">User </span>newUser = <span style="color: blue">new </span><span style="color: #2b91af">User</span>();
        newUser.ID = ID;
        DB.Users.InsertOnSubmit(newUser);
        DB.SubmitChanges();
      }
    }
  }</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>The method uses LINQ C# Comprehension Syntax (&#8220;<span style="color: blue">from </span>user <span style="color: blue">in </span>DB.Users &#8230;&#8221;) to perform a query. It then uses the DataContext to do an Insert when the changes are submitted.</p>
<p>I created a unit test for this method, and it gave me a glowing green light.</p>
<p>Now, I want to add a similar method which uses a different property for comparison. The method would be identical to the first, except for the &#8220;where&#8221; query and the initialization of the new User object. I don&#8217;t want to repeat myself, as that might lead to bugs, so I want to refactor out the common code. I&#8217;m going to do it using lamda expressions.</p>
<h2>Refactoring using lambda expressions</h2>
<p>I could go into my design decisions here, but that&#8217;s not the point of this post. I&#8217;ll just give you the answer &#8211; what I want my class to look like.</p>
<p>Basically, I want to end up with 2 methods which only differentiate on the parts I need them too:</p>
<pre class="code"><span style="color: blue">public void </span>CreateIDUser(<span style="color: blue">string </span>ID) {
  CreateUser(
    user =&gt; user.ID == ID,
    user =&gt; user.ID = ID);
}

<span style="color: blue">public void </span>CreateNamedUser(<span style="color: blue">string </span>name) {
  CreateUser(
    user =&gt; user.Name == name,
    user =&gt; user.Name = name);
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>I create a private method called CreateUser which does the repetitive work:</p>
<pre class="code"><span style="color: blue">private void </span>CreateUser(<span style="color: #2b91af">Func</span>&lt;<span style="color: #2b91af">User</span>, <span style="color: blue">bool</span>&gt; compare, <span style="color: #2b91af">Action</span>&lt;<span style="color: #2b91af">User</span>&gt; initialize) {
  <span style="color: blue">var </span>DB = <span style="color: blue">new </span><span style="color: #2b91af">DBDataContext</span>();
  <span style="color: blue">var </span>existingUsers = <span style="color: blue">from </span>user <span style="color: blue">in </span>DB.Users
                      <span style="color: blue">where </span>compare(user)
                      <span style="color: blue">select </span>user;

  <span style="color: blue">if </span>(existingUsers.Count() == 0) {
    <span style="color: #2b91af">User </span>newUser = <span style="color: blue">new </span><span style="color: #2b91af">User</span>();
    initialize(newUser);
    DB.Users.InsertOnSubmit(newUser);
    DB.SubmitChanges();
  }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Now, this compiles, but when I run my existing test, I get a nasty red light, and the exception message:</p>
<blockquote>
<p>&#8220;System.Object DynamicInvoke(System.Object[])&#8217; has no supported translation to SQL.&#8221;</p>
</blockquote>
<p>What&#8217;s wrong? The problem lies in the query itself, which is using expressions, not pure delegates. My Func&lt;User, bool&gt; cannot be used by LINQ to SQL to do its work. Instead, I have to use an Expression.</p>
<h2>Using an Expression&lt;Func&lt;T, bool&gt;&gt;</h2>
<p>Instead of a simple &#8220;Func&lt;User, bool&gt;&#8221;, I have to declare my parameter as &#8220;Expression&lt;Func&lt;User, bool&gt;&#8221;. That is what LINQ to SQL expects to use for deferred queries. The good news is that I can use an expression by defining it in the method accepting the lamda; the C# compiler can translate my existing lamda expressions from delegates to expressions without any extra work.</p>
<p>Once that&#8217;s done, there&#8217;s one more caveat. You cannot use C# comprehension syntax with an expression. You have to use the standard LINQ query syntax instead.</p>
<p>Here&#8217;s what the final class looks like after the refactoring.</p>
<pre class="code"><span style="color: blue">public class </span><span style="color: #2b91af">UserController </span>{
  <span style="color: blue">public void </span>CreateIDUser(<span style="color: blue">string </span>ID) {
    CreateUser(
      user =&gt; user.ID == ID,
      user =&gt; user.ID = ID);
  }

  <span style="color: blue">public void </span>CreateNamedUser(<span style="color: blue">string </span>name) {
    CreateUser(
      user =&gt; user.Name == name,
      user =&gt; user.Name = name);
  }

  <span style="color: blue">private void </span>CreateUser(<span style="color: #2b91af">Expression</span>&lt;<span style="color: #2b91af">Func</span>&lt;<span style="color: #2b91af">User</span>, <span style="color: blue">bool</span>&gt;&gt; compare, <span style="color: #2b91af">Action</span>&lt;<span style="color: #2b91af">User</span>&gt; initialize) {
    <span style="color: blue">var </span>MeetUp = <span style="color: blue">new </span><span style="color: #2b91af">MeetUpDataContext</span>();
    <span style="color: #2b91af">IQueryable</span>&lt;<span style="color: #2b91af">User</span>&gt; existingUsers = MeetUp.Users
      .AsQueryable&lt;<span style="color: #2b91af">User</span>&gt;()
      .Where(compare);

    <span style="color: blue">if </span>(existingUsers.Count() == 0) {
      <span style="color: #2b91af">User </span>newUser = <span style="color: blue">new </span><span style="color: #2b91af">User</span>();
      initialize(newUser);
      MeetUp.Users.InsertOnSubmit(newUser);
      MeetUp.SubmitChanges();
    }
  }
}</pre>
<p>After that, I get my green light back, and we&#8217;re all happy.</p>

<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F01%2F16%2Fusing-lambda-expressions-with-linq-to-sql%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
]]></content:encoded>
			<wfw:commentRss>http://www.richardbushnell.net/2008/01/16/using-lambda-expressions-with-linq-to-sql/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Inserting into a Table with LINQ to SQL</title>
		<link>http://www.richardbushnell.net/2008/01/15/inserting-into-a-table-with-linq-to-sql/</link>
		<comments>http://www.richardbushnell.net/2008/01/15/inserting-into-a-table-with-linq-to-sql/#comments</comments>
		<pubDate>Tue, 15 Jan 2008 13:40:07 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[Software]]></category>

		<guid isPermaLink="false">http://richardbushnell.net/index.php/2008/01/15/inserting-into-a-table-with-linq-to-sql/</guid>
		<description><![CDATA[While creating a little project, I wanted to know how to insert an object into a table using LINQ to SQL. Using Intellisense it wasn&#8217;t obvious at all. Scott Guthrie wrote a post on how do it. Unfortunately, the method name has changed since he did it, so you need to call InsertOnSubmit on the [...]]]></description>
			<content:encoded><![CDATA[
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F01%2F15%2Finserting-into-a-table-with-linq-to-sql%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<br><p>While creating a little project, I wanted to know how to insert an object into a table using LINQ to SQL. Using Intellisense it wasn&#8217;t obvious at all.</p>
<p><a href="http://weblogs.asp.net/scottgu" target="_blank">Scott Guthrie</a> wrote <a href="http://weblogs.asp.net/scottgu/archive/2007/07/11/linq-to-sql-part-4-updating-our-database.aspx" target="_blank">a post on how do it</a>. Unfortunately, the method name has changed since he did it, so you need to call InsertOnSubmit on the Table instead of Add, as he described it.</p>
<p>Phew! Getting that far was hard enough!</p>

<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F01%2F15%2Finserting-into-a-table-with-linq-to-sql%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
]]></content:encoded>
			<wfw:commentRss>http://www.richardbushnell.net/2008/01/15/inserting-into-a-table-with-linq-to-sql/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using LINQ To SQL&#8217;s DataContext in a Multi-Tier Application</title>
		<link>http://www.richardbushnell.net/2008/01/03/using-linq-to-sqls-datacontext-in-a-multi-tier-application/</link>
		<comments>http://www.richardbushnell.net/2008/01/03/using-linq-to-sqls-datacontext-in-a-multi-tier-application/#comments</comments>
		<pubDate>Wed, 02 Jan 2008 22:00:18 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[LINQ SQL DataContext]]></category>

		<guid isPermaLink="false">http://richardbushnell.net/index.php/2008/01/03/using-linq-to-sqls-datacontext-in-a-multi-tier-application/</guid>
		<description><![CDATA[I&#8217;m still reading the excellent C# 3.0 in a Nutshell: A Desktop Quick Reference (In a Nutshell (O&#8217;Reilly)), by Ben and Joseph Albahari. It answers a popular question: how do I use a DataContext object in LINQ within a multi-tier application? According to the authors, you cannot use the DataContext at an application or static [...]]]></description>
			<content:encoded><![CDATA[
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F01%2F03%2Fusing-linq-to-sqls-datacontext-in-a-multi-tier-application%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<br><p><a href="http://www.amazon.com/gp/product/0596527578?ie=UTF8&amp;tag=netsmoo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0596527578"><img style="margin: 0px 20px 20px 0px" src="/images/21wTNREvxHL._AA_SL160_.jpg" align="left" border="0" /></a><img style="margin: 0px; border-top-style: none! important; border-right-style: none! important; border-left-style: none! important; border-bottom-style: none! important" height="1" alt="" src="http://www.assoc-amazon.com/e/ir?t=netsmoo-20&amp;l=as2&amp;o=1&amp;a=0596527578" width="1" border="0" /></p>
<p>I&#8217;m still reading the excellent <a href="http://www.amazon.com/gp/product/0596527578?ie=UTF8&amp;tag=netsmoo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0596527578">C# 3.0 in a Nutshell: A Desktop Quick Reference (In a Nutshell (O&#8217;Reilly))</a><img src="http://www.assoc-amazon.com/e/ir?t=netsmoo-20&amp;l=as2&amp;o=1&amp;a=0596527578" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />, by Ben and Joseph Albahari. It answers a popular question: how do I use a DataContext object in LINQ within a multi-tier application?</p>
<p>According to the authors, you cannot use the DataContext at an application or static level, or use a single instance for all requests, as it is not thread-safe. It has to be recreated for each request.</p>
<p>I need to look into this more.</p>

<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F01%2F03%2Fusing-linq-to-sqls-datacontext-in-a-multi-tier-application%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
]]></content:encoded>
			<wfw:commentRss>http://www.richardbushnell.net/2008/01/03/using-linq-to-sqls-datacontext-in-a-multi-tier-application/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

