<?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 to SQL</title>
	<atom:link href="http://www.richardbushnell.net/tag/linq-to-sql/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>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>A Pure ASP.Net Grid with Grouping</title>
		<link>http://www.richardbushnell.net/2008/03/02/a-pure-aspnet-grid-with-grouping/</link>
		<comments>http://www.richardbushnell.net/2008/03/02/a-pure-aspnet-grid-with-grouping/#comments</comments>
		<pubDate>Sun, 02 Mar 2008 19:26:16 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Grouping]]></category>
		<category><![CDATA[LINQ to SQL]]></category>
		<category><![CDATA[LinqDataSource]]></category>
		<category><![CDATA[ListView]]></category>

		<guid isPermaLink="false">http://richardbushnell.net/index.php/2008/03/02/a-pure-aspnet-grid-with-grouping/</guid>
		<description><![CDATA[One of my favorite bloggers is Matt Berseth. Nearly once a week he comes up with a post where he does something amazing with the standard ASP.Net controls. I usually read his posts in awe. He&#8217;s really good. But he&#8217;s not only is a good developer, he&#8217;s a great writer. Even though his posts are [...]]]></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%2F02%2Fa-pure-aspnet-grid-with-grouping%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>One of my favorite bloggers is <a href="http://mattberseth.com/blog">Matt Berseth</a>. Nearly once a week he comes up with a post where he does something amazing with the standard ASP.Net controls. I usually read his posts in awe. He&#8217;s really good.</p>
<p>But he&#8217;s not only is a good developer, he&#8217;s a great writer. Even though his posts are concise and straight to the point, most of them are pages long. You can really learn a lot from following his instructions.</p>
<p>He&#8217;s so good, in fact, that he regularly gets a mention on Scott Guthrie&#8217;s posts.</p>
<p>One of my favorite posts of his was where he used LINQ-to-SQL, a LinqDataSource control, and an ASP.Net ListView control &#8211; all new in .Net 3.5 &#8211; and made a grid with grouping functionality. He did it all in a standard way, and didn&#8217;t use any funny tricks.</p>
<p><a href="http://mattberseth.com/blog/2008/01/building_a_grouping_grid_with.html"><img style="border-right: 0px; border-top: 0px; margin: 0px; border-left: 0px; border-bottom: 0px" height="350" alt="image" src="http://www.richardbushnell.net/wp-content/uploads/2008/03/image1.png" width="465" border="0" /></a> </p>
<p>Here&#8217;s a link to the article:</p>
<h5><a href="http://mattberseth.com/blog/2008/01/building_a_grouping_grid_with.html">Building a Grouping Grid with the ASP.NET 3.5 LinqDataSource and ListView Controls</a></h5>
<p>Enjoy!</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%2F02%2Fa-pure-aspnet-grid-with-grouping%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/02/a-pure-aspnet-grid-with-grouping/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>
	</channel>
</rss>

