<?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>David DeWinter &#187; LINQ to SQL</title>
	<atom:link href="http://blogs.rev-net.com/ddewinter/category/linq-to-sql/feed/" rel="self" type="application/rss+xml" />
	<link>http://blogs.rev-net.com/ddewinter</link>
	<description>A Developer's Melting Pot: LINQ to SQL, Entity Framework, .NET Security...</description>
	<lastBuildDate>Tue, 02 Mar 2010 16:02:48 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>LINQ Expression Trees and the Specification Pattern</title>
		<link>http://blogs.rev-net.com/ddewinter/2009/05/31/linq-expression-trees-and-the-specification-pattern/</link>
		<comments>http://blogs.rev-net.com/ddewinter/2009/05/31/linq-expression-trees-and-the-specification-pattern/#comments</comments>
		<pubDate>Mon, 01 Jun 2009 00:42:06 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[Design]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[LINQ to SQL]]></category>

		<guid isPermaLink="false">http://blogs.rev-net.com/ddewinter/2009/05/31/linq-expression-trees-and-the-specification-pattern/</guid>
		<description><![CDATA[Over the past couple of months I have tried to immerse myself in domain-driven design, which includes learning about its purpose, the methodology, and the domain patterns presented in Evans&#8217; book and built upon in many other venues (blogs, conferences, etc.). While I have not worked on a full-fledged DDD project, I have fiddled with [...]]]></description>
			<content:encoded><![CDATA[<p>Over the past couple of months I have tried to immerse myself in domain-driven design, which includes learning about its purpose, the methodology, and the domain patterns presented in <a href="http://www.amazon.com/gp/product/0321125215">Evans&#8217; book</a> and built upon in many other venues (blogs, conferences, etc.). While I have not worked on a full-fledged DDD project, I have fiddled with a lot of patterns. One of these is the <span class="smallcaps">Specification</span> pattern, which says to introduce a predicate-like <span class="smallcaps">Value Object</span> into the domain layer whose purpose is to evaluate whether an object meets some criteria. From what I&#8217;ve read in Evans&#8217; book, specification objects typically have an isSatisfiedBy method that takes a domain object and returns a boolean. The specification therefore encapsulates a predicate that can be used to test an object to see if it satisfies the criteria. </p>
<p><a href="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2009/05/image8.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2009/05/image-thumb8.png" width="169" height="41" /></a> </p>
</p>
<p>The problem that Evans later calls out is that of querying a data store using specification objects as filters. Because using the specification to filter records from the database <strong>requires</strong> that those records be selected and reconstituted into objects, it can be inefficient for some applications to use specification objects as is. (Imagine using a specification object on one million rows in the Customer table just to find the gold Customers!) Surely we can do better.</p>
<h3>Ideas</h3>
<p>One idea in the book is to allow a repository to help with the implementation and utilize <a href="http://en.wikipedia.org/wiki/Double_dispatch">double dispatch</a> to keep the separation of domain and infrastructure in tact. Application code calls a method on a repository to query for objects based on a specification. That repository passes itself to a method on the specification object, so the specification can utilize the repository&#8217;s power to query for the objects that fulfill the criteria, and then return that data to the application.</p>
<p><a href="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2009/05/image9.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2009/05/image-thumb9.png" width="520" height="230" /></a> </p>
<p>Another alternative is to harness the power of LINQ and expression trees to represent the predicate that the specification object encapsulates. This means that we can (1) use the expression trees in the infrastructure to let the data store take care of filtering and (2) still represent our rule in one location without resorting to compromises in the repository API.</p>
<p>Expression trees are abstract syntax trees that can represent the predicates that specification objects strive to encapsulate. With these expression trees, certain O/R mappers like LINQ to SQL, the Entity Framework, and LLBLGen Pro can determine the intent of the code and translate it into the corresponding T-SQL code to run against the database.</p>
<p>Creating an expression tree is very simple. In fact, if you&#8217;ve used any of the O/R mappers I mentioned above, you&#8217;ve probably used them already. Here&#8217;s an example of an expression tree being used in LINQ to SQL to generate the WHERE clause in the corresponding T-SQL query below.</p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: #2b91af">NorthwindDataContext</span> db = <span style="color: blue">new</span> <span style="color: #2b91af">NorthwindDataContext</span>();</p>
<p style="margin: 0px">db.Products.Single(p =&gt; p.ProductName == <span style="color: #a31515">&quot;Aniseed Syrup&quot;</span>);</p>
</p></div>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">SELECT </span>[t0].[ProductID], [t0].[ProductName], [t0].[SupplierID], [t0].[CategoryID], [t0].[QuantityPerUnit], [t0].[UnitPrice], [t0].[UnitsInStock], [t0].[UnitsOnOrder], [t0].[ReorderLevel], [t0].[Discontinued]</p>
<p style="margin: 0px"><span style="color: blue">FROM </span>[dbo].[Products] <span style="color: blue">AS </span>[t0]</p>
<p style="margin: 0px"><span style="color: blue">WHERE </span>[t0].[ProductName] = @p0</p>
<p style="margin: 0px"><span style="color: green">&#8211; @p0: Input NVarChar (Size = 13; Prec = 0; Scale = 0) [Aniseed Syrup]</span></p>
<p style="margin: 0px"><span style="color: green">&#8211; Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1</span></p>
</p></div>
<p>Normally the lambda expression &#8216;p =&gt; p.ProductName == &quot;Aniseed Syrup&quot;&#8217; would be treated as a <a href="http://msdn.microsoft.com/en-us/library/bb549151.aspx">Func&lt;Product, bool&gt;</a>. However, in this particular usage the compiler infers that it is an <a href="http://msdn.microsoft.com/en-us/library/bb335710.aspx">Expression&lt;Func&lt;Product, bool&gt;&gt;</a>. The difference means that the LINQ to SQL library no longer has a method pointer. <strong>Instead, it has a tree which represents what that method does</strong>. LINQ to SQL can visit the nodes in this tree and translate what it finds into SQL without ever invoking the code itself. A simple Func does not have that capability; it is simply a method pointer, like any other delegate type.</p>
<p>I hope you start to see how expression trees and the specification pattern can be very powerful together. If in addition to exposing an isSatisfiedBy method on the specification object, we add something which exposes the raw Expression, the repository can compose this Expression into the query and filter the results using the infrastructure. Let&#8217;s look at some code.</p>
<p>For this example, let&#8217;s continue to use the Products table from Northwind. The specification we implement here will tell us whether a product is a low stock product i.e. whether the number of units in stock for a particular product falls below a certain threshold. That threshold is defined in another system, so we will feed that data to the specification.</p>
<p>Let&#8217;s start with the basics. Here&#8217;s the base class for all Specifications. Instead of using IsSatisfiedBy, we expose a method which returns an expression tree of type Expression&lt;Func&lt;T, bool&gt;&gt;.</p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">abstract</span> <span style="color: blue">class</span> <span style="color: #2b91af">Specification</span>&lt;T&gt;</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">abstract</span> <span style="color: #2b91af">Expression</span>&lt;<span style="color: #2b91af">Func</span>&lt;T, <span style="color: blue">bool</span>&gt;&gt; IsSatisfied();</p>
<p style="margin: 0px">}</p>
</p></div>
<p>The Expression class is in the System.Linq.Expressions namespace which is a part of System.Core.dll. Remember, this is just a different representation of IsSatisfiedBy; instead of keeping the logic embedded in a method in the specification object, we package the logic in an expression tree. The predicate still receives an object and returns a boolean. Other classes, like the ProductRepository, can now leverage this expression tree to optimize the query it sends to the database.</p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">public partial</span> <span style="color: blue">class</span> <span style="color: #2b91af">ProductRepository</span> : <span style="color: #2b91af">IProductRepository</span></p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: #2b91af">IQueryable</span>&lt;<span style="color: #2b91af">Product</span>&gt; SelectSatisfying(<span style="color: #2b91af">Specification</span>&lt;<span style="color: #2b91af">Product</span>&gt; specification)</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> <span style="color: blue">this</span>.context.Products.Where(specification.IsSatisfied());</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">}</p>
</p></div>
<p>Here we use the Entity Framework to select the Products that match a certain Product Specification. (The field &quot;context&quot; is the ObjectContext, in this case.) However, we could switch this for any data access technology that can leverage expression trees and retrieve similar results.</p>
<p>The next step is to implement the actual specification.</p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">LowStockSpecification</span> : <span style="color: #2b91af">Specification</span>&lt;<span style="color: #2b91af">Product</span>&gt;</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> LowStockSpecification(<span style="color: blue">int</span> lowStockThreshold)</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">this</span>.LowStockThreshold = lowStockThreshold;</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">int</span> LowStockThreshold</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">get</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">set</span>;</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">override</span> <span style="color: #2b91af">Expression</span>&lt;<span style="color: #2b91af">Func</span>&lt;<span style="color: #2b91af">Product</span>, <span style="color: blue">bool</span>&gt;&gt; IsSatisfied()</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> p =&gt; p.UnitsInStock &lt; <span style="color: blue">this</span>.LowStockThreshold;</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">}</p>
</p></div>
<p>Evans says that specifications should be value objects, so I&#8217;ve taken that to heart and made this class immutable. This allows us to make some optimizations with specifications (caching the expression tree, introducing an IsSatisfiedBy by reusing the logic in the expression tree, etc.) if we would like.</p>
<p>This final code snippet shows how to leverage the specification and repository together.</p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">ProductReorderingService</span></p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: #2b91af">IProductRepository</span> productRepository;</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> ProductReorderingService(<span style="color: #2b91af">IProductRepository</span> productRepository)</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">this</span>.productRepository = productRepository;</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">void</span> ReorderLowStockProducts()</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">LowStockSpecification</span> spec = <span style="color: blue">new</span> <span style="color: #2b91af">LowStockSpecification</span>(5);</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">foreach</span> (<span style="color: blue">var</span> p <span style="color: blue">in</span> <span style="color: blue">this</span>.productRepository.SelectSatisfying(spec))</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: green">// Reorder product</span></p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">}</p>
</p></div>
<h3>Composing Specifications</h3>
<p>One property of specifications is that they can be combined to form more interesting predicates. This would allow our ProductRepository to support queries that involve multiple specification instances—for example, a filter that checks for units with low stock OR units whose stock is below their re-order level. The most common implementation I&#8217;ve seen of this requirement involves three new classes, AndSpecification&lt;T&gt;, OrSpecification&lt;T&gt;, and NotSpecification&lt;T&gt;. While it&#8217;s easy enough to implement these when all you worry about is IsSatisfiedBy (<em>e.g. </em>spec1.IsSatisfiedBy(o) &amp;&amp; spec2.IsSatisfiedBy(o) for the AndSpecification&lt;T&gt;), it&#8217;s actually a bit tricky to do this with expressions.</p>
<p>Fortunately, it&#8217;s not impossible, and Colin Meek has it documented on his <a href="http://blogs.msdn.com/meek/archive/2008/05/02/linq-to-entities-combining-predicates.aspx">blog post</a> about combining predicates in the Entity Framework, but the concepts apply more generally to any provider that can use expression trees. Be careful though; if you&#8217;re using the Entity Framework you will have to copy more code than you would with LINQ to SQL. I am not sure about LLBLGen Pro.</p>
<p>If you use the extension methods that Colin provides for AND&#8217;ing and OR&#8217;ing expression trees together, you&#8217;ll end up with these implementations of AndSpecification&lt;T&gt; and OrSpecification&lt;T&gt;:</p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">AndSpecification</span>&lt;T&gt; : <span style="color: #2b91af">Specification</span>&lt;T&gt;</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: #2b91af">Specification</span>&lt;T&gt; spec1;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: #2b91af">Specification</span>&lt;T&gt; spec2;</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> AndSpecification(<span style="color: #2b91af">Specification</span>&lt;T&gt; spec1, <span style="color: #2b91af">Specification</span>&lt;T&gt; spec2)</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">this</span>.spec1 = spec1;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">this</span>.spec2 = spec2;</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">override</span> <span style="color: #2b91af">Expression</span>&lt;<span style="color: #2b91af">Func</span>&lt;T, <span style="color: blue">bool</span>&gt;&gt; IsSatisfied()</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> <span style="color: blue">this</span>.spec1.IsSatisfied().And(<span style="color: blue">this</span>.spec2.IsSatisfied());</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">}</p>
</p></div>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">OrSpecification</span>&lt;T&gt; : <span style="color: #2b91af">Specification</span>&lt;T&gt;</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: #2b91af">Specification</span>&lt;T&gt; spec1;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: #2b91af">Specification</span>&lt;T&gt; spec2;</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> OrSpecification(<span style="color: #2b91af">Specification</span>&lt;T&gt; spec1, <span style="color: #2b91af">Specification</span>&lt;T&gt; spec2)</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">this</span>.spec1 = spec1;</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">this</span>.spec2 = spec2;</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">override</span> <span style="color: #2b91af">Expression</span>&lt;<span style="color: #2b91af">Func</span>&lt;T, <span style="color: blue">bool</span>&gt;&gt; IsSatisfied()</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> <span style="color: blue">this</span>.spec1.IsSatisfied().Or(<span style="color: blue">this</span>.spec2.IsSatisfied());</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">}</p>
</p></div>
<p>We&#8217;ll have to write the NotSpecification&lt;T&gt; ourselves, but this is not as involved as And and Or, even with the Entity Framework. We essentially take the body of the expression tree from the original specification and negate the result. Using the patterns you can read about in Colin&#8217;s blog post, we can use the following class as our NotSpecification&lt;T&gt;.</p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">NotSpecification</span>&lt;T&gt; : <span style="color: #2b91af">Specification</span>&lt;T&gt;</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: #2b91af">Specification</span>&lt;T&gt; originalSpec;</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> NotSpecification(<span style="color: #2b91af">Specification</span>&lt;T&gt; originalSpec)</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">this</span>.originalSpec = originalSpec;</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">override</span> <span style="color: #2b91af">Expression</span>&lt;<span style="color: #2b91af">Func</span>&lt;T, <span style="color: blue">bool</span>&gt;&gt; IsSatisfied()</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">Expression</span>&lt;<span style="color: #2b91af">Func</span>&lt;T, <span style="color: blue">bool</span>&gt;&gt; originalTree = <span style="color: blue">this</span>.originalSpec.IsSatisfied();</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> <span style="color: #2b91af">Expression</span>.Lambda&lt;<span style="color: #2b91af">Func</span>&lt;T, <span style="color: blue">bool</span>&gt;&gt;(</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">Expression</span>.Not(originalTree.Body),</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; originalTree.Parameters.Single()</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; );</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">} </p>
</p></div>
<h3>This is all well and good, but doesn&#8217;t this tie my domain to my infrastructure?</h3>
<p>I think you can find arguments for both viewpoints. The specification pattern allows you to encapsulate a predicate to determine whether an object matches a condition. My opinion is whether that predicate is exposed as a method or an expression tree, the intent is preserved and there is one place where the criteria for a specification are checked. It does require you to use infrastructure that can utilize expression trees, but I would say that there is nothing about expression trees that tie them to the infrastructure layer directly. The details of the underlying data store have not leaked into the domain layer. If I had a provider that could use expression trees for XML or an object database store, then my domain layer would not change.</p>
<p>I enjoy learning about DDD and what other folks have done in this area. I&#8217;d love to hear your feedback.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:2588ec66-a9e8-410d-b383-cafc9cc514c8" class="wlWriterEditableSmartContent">Technorati Tags: <a href="http://technorati.com/tags/Domain-Driven+Design" rel="tag">Domain-Driven Design</a>,<a href="http://technorati.com/tags/Specification" rel="tag">Specification</a>,<a href="http://technorati.com/tags/LINQ" rel="tag">LINQ</a>,<a href="http://technorati.com/tags/expression+trees" rel="tag">expression trees</a>,<a href="http://technorati.com/tags/DDD" rel="tag">DDD</a></div>
]]></content:encoded>
			<wfw:commentRss>http://blogs.rev-net.com/ddewinter/2009/05/31/linq-expression-trees-and-the-specification-pattern/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Using LINQ to SQL and EF in Sharepoint under Medium Trust</title>
		<link>http://blogs.rev-net.com/ddewinter/2009/04/22/using-linq-to-sql-and-ef-in-sharepoint-under-medium-trust/</link>
		<comments>http://blogs.rev-net.com/ddewinter/2009/04/22/using-linq-to-sql-and-ef-in-sharepoint-under-medium-trust/#comments</comments>
		<pubDate>Thu, 23 Apr 2009 03:35:24 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[LINQ to SQL]]></category>
		<category><![CDATA[medium trust]]></category>
		<category><![CDATA[partial trust]]></category>
		<category><![CDATA[sharepoint]]></category>

		<guid isPermaLink="false">http://blogs.rev-net.com/ddewinter/2009/04/22/using-linq-to-sql-and-ef-in-sharepoint-under-medium-trust/</guid>
		<description><![CDATA[Code Access Security (CAS) is a large area of the .NET Framework that doesn&#8217;t often get the developer attention it deserves—at least, until it causes problems. Very recently I fielded a question on why the Entity Framework throws a SecurityException when executing a query in a Sharepoint-hosted web site run under medium trust. The answer, [...]]]></description>
			<content:encoded><![CDATA[<p>Code Access Security (CAS) is a large area of the .NET Framework that doesn&#8217;t often get the developer attention it deserves—at least, until it causes problems. Very recently I fielded a question on why the Entity Framework throws a SecurityException when executing a query in a Sharepoint-hosted web site run under medium trust. The answer, I thought, is definitely worth sharing.</p>
<h3>The Repro</h3>
<p>The failure looks very similar to the exception described on <a href="http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataservices/thread/0dc87db4-c145-456b-a19f-eebc16c09efb/">this forum post</a>. However, the forum post describes a SecurityException thrown from an XBAP application, not an ASP.NET application. The reason for the failure, however, is the same. Take the following EF query, for example:</p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">var</span> customer = (<span style="color: blue">from</span> c <span style="color: blue">in</span> db.Customers</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">where</span> c.CustomerID == <span style="color: #a31515">&quot;ALFKA&quot;</span></p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">select</span> c).FirstOrDefault();</p>
</p></div>
<p>It&#8217;s a very simple query, which runs in medium trust without any errors. But consider the more useful use case:</p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">public</span> <span style="color: #2b91af">Customer</span> GetCustomerById(<span style="color: blue">string</span> customerId)</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">using</span> (<span style="color: #2b91af">NorthwindEntities</span> db = <span style="color: blue">new</span> <span style="color: #2b91af">NorthwindEntities</span>())</p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> (<span style="color: blue">from</span> c <span style="color: blue">in</span> db.Customers</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">where</span> c.CustomerID == customerId</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">select</span> c).FirstOrDefault();</p>
<p style="margin: 0px">&#160;&#160;&#160; }</p>
<p style="margin: 0px">}</p>
</p></div>
<p>The fundamental difference is that we&#8217;re using a parameter value to supply the criterion for our query. This throws the following exception in Sharepoint under medium trust:</p>
<blockquote><p>System.MethodAccessException was unhandled by user code      <br />&#160; Message=&quot;System.Runtime.CompilerServices.StrongBox`1..ctor(System.__Canon)&quot;       <br />&#160; Source=&quot;mscorlib&quot;       <br />&#160; StackTrace:       <br />&#160;&#160;&#160;&#160;&#160;&#160; at System.Reflection.MethodBase.PerformSecurityCheck(Object obj, RuntimeMethodHandle method, IntPtr parent, UInt32 invocationFlags)       <br />&#160;&#160;&#160;&#160;&#160;&#160; at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)       <br />&#160;&#160;&#160;&#160;&#160;&#160; at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)       <br />&#160;&#160;&#160;&#160;&#160;&#160; at System.Linq.Expressions.ExpressionCompiler.AddGlobal(Type type, Object value)       <br />&#160;&#160;&#160;&#160;&#160;&#160; at System.Linq.Expressions.ExpressionCompiler.GenerateConstant(ILGenerator gen, Type type, Object value, StackType ask)       <br />&#160;&#160;&#160;&#160;&#160;&#160; at System.Linq.Expressions.ExpressionCompiler.Generate(ILGenerator gen, Expression node, StackType ask)       <br />&#160;&#160;&#160;&#160;&#160;&#160; at System.Linq.Expressions.ExpressionCompiler.GenerateMemberAccess(ILGenerator gen, Expression expression, MemberInfo member, StackType ask)       <br />&#160;&#160;&#160;&#160;&#160;&#160; at System.Linq.Expressions.ExpressionCompiler.Generate(ILGenerator gen, Expression node, StackType ask)       <br />&#160;&#160;&#160;&#160;&#160;&#160; at System.Linq.Expressions.ExpressionCompiler.GenerateLambda(LambdaExpression lambda)       <br />&#160;&#160;&#160;&#160;&#160;&#160; at System.Linq.Expressions.ExpressionCompiler.CompileDynamicLambda(LambdaExpression lambda)       <br />&#160;&#160;&#160;&#160;&#160;&#160; at System.Linq.Expressions.ExpressionCompiler.Compile(LambdaExpression lambda)       <br />&#160;&#160;&#160;&#160;&#160;&#160; at System.Linq.Expressions.ExpressionCompiler.Compile[D](Expression`1 lambda)       <br />&#160;&#160;&#160;&#160;&#160;&#160; at System.Linq.EnumerableExecutor`1.Execute()       <br />&#160;&#160;&#160;&#160;&#160;&#160; at System.Linq.EnumerableExecutor`1.ExecuteBoxed()       <br />&#160;&#160;&#160;&#160;&#160;&#160; at System.Data.Objects.ELinq.ClosureBinding.ParameterBinding.EvaluateBinding()       <br />&#160;&#160;&#160;&#160;&#160;&#160; at System.Data.Objects.ELinq.ClosureBinding.TryCreateClosureBinding(Expression expression, ClrPerspective perspective, Boolean allowLambda, HashSet`1 closureCandidates, ClosureBinding&amp; binding, TypeUsage&amp; typeUsage)       <br />&#160;&#160;&#160;&#160;&#160;&#160; at System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)       <br />&#160;&#160;&#160;&#160;&#160;&#160; at System.Data.Objects.ELinq.ExpressionConverter.EqualsTranslator.TypedTranslate(ExpressionConverter parent, BinaryExpression linq)       <br />&#160;&#160;&#160;&#160;&#160;&#160; at System.Data.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq)       <br />&#160;&#160;&#160;&#160;&#160;&#160; at System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)       <br />&#160;&#160;&#160;&#160;&#160;&#160; at System.Data.Objects.ELinq.ExpressionConverter.TranslateLambda(LambdaExpression lambda, DbExpression input)       <br />&#160;&#160;&#160;&#160;&#160;&#160; at System.Data.Objects.ELinq.ExpressionConverter.MethodCallTranslator.OneLambdaTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, DbExpression&amp; source, DbExpressionBinding&amp; sourceBinding, DbExpression&amp; lambda)       <br />&#160;&#160;&#160;&#160;&#160;&#160; at System.Data.Objects.ELinq.ExpressionConverter.MethodCallTranslator.OneLambdaTranslator.Translate(ExpressionConverter parent, MethodCallExpression call)       <br />&#160;&#160;&#160;&#160;&#160;&#160; at System.Data.Objects.ELinq.ExpressionConverter.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq)       <br />&#160;&#160;&#160;&#160;&#160;&#160; at System.Data.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq)       <br />&#160;&#160;&#160;&#160;&#160;&#160; at System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)       <br />&#160;&#160;&#160;&#160;&#160;&#160; at System.Data.Objects.ELinq.ExpressionConverter.Convert()       <br />&#160;&#160;&#160;&#160;&#160;&#160; at System.Data.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable`1 forMergeOption)       <br />&#160;&#160;&#160;&#160;&#160;&#160; at System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)       <br />…       <br />&#160; InnerException: System.Security.SecurityException       <br />&#160;&#160;&#160;&#160;&#160;&#160; Message=&quot;<strong>Request for the permission of type &#8216;System.Security.Permissions.ReflectionPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089&#8242; failed.</strong>&quot;       <br />&#160;&#160;&#160;&#160;&#160;&#160; Source=&quot;mscorlib&quot;       <br />&#160;&#160;&#160;&#160;&#160;&#160; StackTrace:       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; at System.Security.CodeAccessSecurityEngine.ThrowSecurityException(Assembly asm, PermissionSet granted, PermissionSet refused, RuntimeMethodHandle rmh, SecurityAction action, Object demand, IPermission permThatFailed)       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; at System.Security.CodeAccessSecurityEngine.CheckSetHelper(PermissionSet grants, PermissionSet refused, PermissionSet demands, RuntimeMethodHandle rmh, Object assemblyOrString, SecurityAction action, Boolean throwException)       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; at System.Security.PermissionSetTriple.CheckSetDemand(PermissionSet demandSet, PermissionSet&amp; alteredDemandset, RuntimeMethodHandle rmh)       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; at System.Security.PermissionListSet.CheckSetDemand(PermissionSet pset, RuntimeMethodHandle rmh)       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; at System.Security.PermissionListSet.DemandFlagsOrGrantSet(Int32 flags, PermissionSet grantSet)       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; at System.Security.CodeAccessSecurityEngine.ReflectionTargetDemandHelper(Int32 permission, PermissionSet targetGrant, CompressedStack securityContext)       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; at System.Security.CodeAccessSecurityEngine.ReflectionTargetDemandHelper(Int32 permission, PermissionSet targetGrant)       <br />&#160;&#160;&#160;&#160;&#160;&#160; InnerException: </p>
</blockquote>
<h3>A Closer Look</h3>
<p>The bolded text clues us into the real problem—a demand for ReflectionPermission failed. But we&#8217;re not doing reflection…or are we? </p>
<p>In order for our C# code to access the value of the customerId parameter, the compiler creates a new private nested class with a single public field for the customerId. When creating the expression tree to represent the query above, the compiler inserts code to instantiate this new class and adds that instance as a node in the tree. When the Entity Framework later processes the expression tree, it attempts to create an instance of that private class. (See above—RuntimeConstructorInfo.Invoke)</p>
<p>So what does permissions does this call to RuntimeConstructorInfo.Invoke require? In .NET 3.5, the demand is satisfied when all assemblies in the stack trace have one of the following sets of permissions:</p>
<ol>
<li>ReflectionPermission with ReflectionPermissionFlag.MemberAccess </li>
<li>ReflectionPermission with ReflectionPermissionFlag.RestrictedMemberAccess UNION PermissionSet of the assembly which contains the member being reflected. </li>
</ol>
<p>In .NET 2.0, ASP.NET medium trust did not allow reflection on non-public members. When Microsoft released .NET 3.5, the ReflectionPermission featured a new option: RestrictedMemberAccess (RMA). The concept is a bit tricky to understand the first time, so here&#8217;s an example of what RMA really means.</p>
<p>Take two assemblies, <em>A</em> and <em>B</em>. Assembly <em>A</em> is loaded in medium trust, and Assembly <em>B </em>is loaded in medium trust. Because both assemblies have the same trust level and because medium trust grants RMA, Assembly <em>A</em> can use reflection to discover non-public members in Assembly <em>B</em>. If a new assembly, Assembly <em>C</em>, is loaded in full trust, then Assembly <em>A</em> <strong>cannot</strong> use reflection to discover non-public members in Assembly <em>C</em>. If Assembly <em>A </em>is granted ReflectionPermission with MemberAccess, then it can use reflection on any assembly to discover any non-public member. Shawn Farkas discusses RMA in more detail <a href="http://blogs.msdn.com/shawnfa/archive/2006/09/29/777047.aspx">here</a>.</p>
<p>Assuming all this makes sense, let&#8217;s return to the problem. Our assembly is loaded in medium trust, and the code tries to reflect into the same assembly to find this non-public type generated by the compiler. However, the demand for ReflectionPermission still fails. This doesn&#8217;t make sense; the assembly&#8217;s permission set is equal to itself, and medium trust grants RMA…</p>
<h3>The Solution</h3>
<p>The key here is that medium trust in Sharepoint is not what we expect. The web.config file for our application points us in the right direction:</p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">&lt;</span><span style="color: #a31515">trust</span><span style="color: blue"> </span><span style="color: red">level</span><span style="color: blue">=</span>&quot;<span style="color: blue">WSS_Medium</span>&quot;<span style="color: blue"> </span><span style="color: red">originUrl</span><span style="color: blue">=</span>&quot;&quot;<span style="color: blue"> /&gt;</span></p>
</p></div>
<p>The WSS_Medium trust level is not the same as the medium trust level offered by ASP.NET. On further investigation in the same web.config file, we see that WSS_Medium is defined in an external policy file:</p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">&lt;</span><span style="color: #a31515">trustLevel</span></p>
<p style="margin: 0px"><span style="color: blue">&#160; </span><span style="color: red">name</span><span style="color: blue">=</span>&quot;<span style="color: blue">WSS_Medium</span>&quot;</p>
<p style="margin: 0px"><span style="color: blue">&#160; </span><span style="color: red">policyFile</span><span style="color: blue">=</span>&quot;<span style="color: blue">C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\config\wss_mediumtrust.config</span>&quot;<span style="color: blue"> /&gt;</span></p>
</p></div>
<p>If you open the policy file, you&#8217;ll see this scavenger hunt leads us to one conclusion: <strong>Sharepoint medium trust does not include ReflectionPermission with RestrictedMemberAccess.</strong> To add this permission, you&#8217;ll need to make two changes to the policy file. First, add the following SecurityClass element to the configuration/mscorlib/security/policy/PolicyLevel/SecurityClasses element.</p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">&lt;</span><span style="color: #a31515">SecurityClass</span></p>
<p style="margin: 0px"><span style="color: blue">&#160; </span><span style="color: red">Name</span><span style="color: blue">=</span>&quot;<span style="color: blue">ReflectionPermission</span>&quot;</p>
<p style="margin: 0px"><span style="color: blue">&#160; </span><span style="color: red">Description</span><span style="color: blue">=</span>&quot;<span style="color: blue">System.Security.Permissions.ReflectionPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</span>&quot;<span style="color: blue">/&gt;</span></p>
</p></div>
<p>Second, add the RMA permission to the configuration/mscorlib/security/policy/PolicyLevel/NamedPermissionSets/PermissionSet[@Name='SPRestricted'] element. It should be the only one with child elements.</p>
<div style="font-family: courier new; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">&lt;</span><span style="color: #a31515">IPermission</span></p>
<p style="margin: 0px"><span style="color: blue">&#160; </span><span style="color: red">class</span><span style="color: blue">=</span>&quot;<span style="color: blue">ReflectionPermission</span>&quot;</p>
<p style="margin: 0px"><span style="color: blue">&#160; </span><span style="color: red">version</span><span style="color: blue">=</span>&quot;<span style="color: blue">1</span>&quot;</p>
<p style="margin: 0px"><span style="color: blue">&#160; </span><span style="color: red">Flags</span><span style="color: blue">=</span>&quot;<span style="color: blue">RestrictedMemberAccess</span>&quot;<span style="color: blue">/&gt;</span></p>
</p></div>
<p>Once the application pool is recycled, the CLR will grant you the RMA permission, and you will be able to run LINQ to SQL and EF queries like those shown above without any fear of SecurityExceptions.</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.rev-net.com/ddewinter/2009/04/22/using-linq-to-sql-and-ef-in-sharepoint-under-medium-trust/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>LINQ to SQL: Updating Entities</title>
		<link>http://blogs.rev-net.com/ddewinter/2009/04/07/linq-to-sql-updating-entities/</link>
		<comments>http://blogs.rev-net.com/ddewinter/2009/04/07/linq-to-sql-updating-entities/#comments</comments>
		<pubDate>Wed, 08 Apr 2009 04:15:53 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[LINQ to SQL]]></category>
		<category><![CDATA[attach]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[optimistic concurrency]]></category>
		<category><![CDATA[update]]></category>

		<guid isPermaLink="false">http://blogs.rev-net.com/ddewinter/2009/04/07/linq-to-sql-updating-entities/</guid>
		<description><![CDATA[Updating entities using any object-relational mapper can be difficult for at least two reasons: (1) the number of update options that these ORM frameworks provide and (2) the complexity of requirements in today&#8217;s business scenarios. With this post I want to discuss a few of the ways that you can update entities in LINQ to [...]]]></description>
			<content:encoded><![CDATA[<p>Updating entities using any object-relational mapper can be difficult for at least two reasons: (1) the number of update options that these ORM frameworks provide and (2) the complexity of requirements in today&#8217;s business scenarios. With this post I want to discuss a few of the ways that you can update entities in LINQ to SQL to fit your particular scenario.</p>
<h3>What Do I Need?</h3>
<p>Before we jump into code, you have to consider how your product requirements influence your update decisions. There are two questions you can ask to help:</p>
<ol>
<li><strong>Can multiple clients update the same database record at the same time?</strong> </li>
<li><strong>If this can happen, what data is saved when multiple simultaneous updates occur?</strong> </li>
</ol>
<p>Question 1&#8217;s answer is usually yes, but there are some environments where it is no, such as single-user applications and applications where users own specific data that nobody else can update.</p>
<p>Question 2 is a bit more complicated. Consider a web application that allows customers to choose their desired seat(s) on a commercial flight. The typical use case is that the customer chooses his seats and successfully submits his choice, but what is the expected behavior when two people choose the same seat and click submit at the same time? Clearly, the customer whose seat choice was saved first should win, and the application should ask the &quot;losing&quot; customer to make another choice.</p>
<p><a href="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2009/04/image.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2009/04/image-thumb.png" width="325" height="214" /></a></p>
<p>Although less common, it&#8217;s also possible for the last update to overwrite all previous changes. This can be very dangerous, especially if the users whose updates were overwritten aren&#8217;t notified. There is also a balance, where the last update wins only if a particular column or set of columns were updated.</p>
<p>I have targeted the discussion of these questions so far toward <a href="http://en.wikipedia.org/wiki/Optimistic_concurrency_control">optimistic concurrency</a> since that is the only concurrency control that LINQ to SQL supports. It is interesting to contrast it with <a href="http://www.ironspeed.com/Designer/3.2.4/WebHelp/Part_IX/What_is_Pessimistic_Concurrency.htm">pessimistic concurrency</a>, but it is out of scope for this post.</p>
<h3>What Can LINQ to SQL Offer?</h3>
<p>Once you&#8217;ve established what you need, it&#8217;s easier to match your requirements with what LINQ to SQL offers. But what <em>does</em> LINQ to SQL offer? Here we&#8217;ll look at a few simple use cases for updates.</p>
<h4>Retrieve Existing Entity, Change Properties, Update </h4>
<p>This is a popular pattern in many object-relational mappers to update entities. The code below shows an example of how to update a Product in the Northwind database using this technique.</p>
<div style="font-family: courier new; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">using</span> (<span style="color: #2b91af">NorthwindDataContext</span> db = <span style="color: blue">new</span> <span style="color: #2b91af">NorthwindDataContext</span>())</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// Retrieve the existing entity. Database Call 1</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: #2b91af">Product</span> product = db.Products.First(p =&gt; p.ProductID == 1);</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// Change the properties. LINQ to SQL knows</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// these specific properties have changed.</span></p>
<p style="margin: 0px">&#160;&#160;&#160; product.UnitsInStock = 14;</p>
<p style="margin: 0px">&#160;&#160;&#160; product.UnitsOnOrder = 100;</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// Flush the changes. Database Call 2</span></p>
<p style="margin: 0px">&#160;&#160;&#160; db.SubmitChanges();</p>
<p style="margin: 0px">}</p>
</p></div>
<p>&#160;</p>
<p>When the application calls the SubmitChanges method, LINQ to SQL knows what specific properties it needs to update in its SQL statement. This is because the DataContext is aware of the Product entity since it was retrieved from the database in the first place.</p>
<p>Note that this approach requires two separate calls to the database—one to select the Product entity and one to update it. In highly contentious situations, it is possible that another client can change that Product entity in between these two database calls. In that case, LINQ to SQL will either allow the last update <strong>or</strong> will throw a <a href="http://msdn.microsoft.com/en-us/library/system.data.linq.changeconflictexception.aspx">ChangeConflictException</a> with the message &quot;Row not found or changed.&quot; Which happens when? The answer is &quot;it depends.&quot;</p>
<p>If you drag tables from the Server Explorer to your DBML designer and start using LINQ to SQL without changing the designer, then your update from the code above will look like this. (To get this information for your queries, set the DataContext.Log property to Console.Out. Alternatively, you can try a <a href="http://damieng.com/blog/2008/07/30/linq-to-sql-log-to-debug-window-file-memory-or-multiple-writers">few other listeners</a>, courtesy of Damien Guard.)</p>
<div style="font-family: courier new; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">UPDATE </span>[dbo].[Products]</p>
<p style="margin: 0px"><span style="color: blue">SET </span>[UnitsInStock] = @p9, [UnitsOnOrder] = @p10</p>
<p style="margin: 0px"><span style="color: blue">WHERE </span>([ProductID] = @p0) <span style="color: blue">AND </span>([ProductName] = @p1) <span style="color: blue">AND </span>([SupplierID] = @p2) <span style="color: blue">AND</span></p>
<p style="margin: 0px">([CategoryID] = @p3) <span style="color: blue">AND </span>([QuantityPerUnit] = @p4) <span style="color: blue">AND </span>([UnitPrice] = @p5) <span style="color: blue">AND</span></p>
<p style="margin: 0px">([UnitsInStock] = @p6) <span style="color: blue">AND </span>([UnitsOnOrder] = @p7) <span style="color: blue">AND </span>([ReorderLevel] = @p8) <span style="color: blue">AND</span></p>
<p style="margin: 0px">(<span style="color: blue">NOT </span>([Discontinued] = 1))</p>
<p style="margin: 0px"><span style="color: green">&#8211; @p0: Input Int (Size = 0; Prec = 0; Scale = 0) [1]</span></p>
<p style="margin: 0px"><span style="color: green">&#8211; @p1: Input NVarChar (Size = 4; Prec = 0; Scale = 0) [Chai]</span></p>
<p style="margin: 0px"><span style="color: green">&#8211; @p2: Input Int (Size = 0; Prec = 0; Scale = 0) [1]</span></p>
<p style="margin: 0px"><span style="color: green">&#8211; @p3: Input Int (Size = 0; Prec = 0; Scale = 0) [1]</span></p>
<p style="margin: 0px"><span style="color: green">&#8211; @p4: Input NVarChar (Size = 18; Prec = 0; Scale = 0) [10 boxes x 20 bags]</span></p>
<p style="margin: 0px"><span style="color: green">&#8211; @p5: Input Money (Size = 0; Prec = 19; Scale = 4) [18.0000]</span></p>
<p style="margin: 0px"><span style="color: green">&#8211; @p6: Input SmallInt (Size = 0; Prec = 0; Scale = 0) [39]</span></p>
<p style="margin: 0px"><span style="color: green">&#8211; @p7: Input SmallInt (Size = 0; Prec = 0; Scale = 0) [0]</span></p>
<p style="margin: 0px"><span style="color: green">&#8211; @p8: Input SmallInt (Size = 0; Prec = 0; Scale = 0) [10]</span></p>
<p style="margin: 0px"><span style="color: green">&#8211; @p9: Input SmallInt (Size = 0; Prec = 0; Scale = 0) [14]</span></p>
<p style="margin: 0px"><span style="color: green">&#8211; @p10: Input SmallInt (Size = 0; Prec = 0; Scale = 0) [100]</span></p>
<p style="margin: 0px"><span style="color: green">&#8211; Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1</span></p>
</p></div>
<p>&#160;</p>
<p>In most cases, this doesn&#8217;t match what you expect. However, it does give you a clue why the ChangeConflictException&#8217;s message is &quot;Row not found or changed.&quot; If the WHERE clause of the SQL UPDATE statement filters out the row you&#8217;re looking for, then no update occurs. And the only case when the WHERE clause would filter it out is when another client has updated one of the properties on the Product between the time it was retrieved and the time it was updated.</p>
<p>So what if you don&#8217;t want this behavior, and you just want to compare the values of the primary keys? This is also a simple change. Navigate to your entity type (Product) in the DBML designer and select all the columns that you do not want to participate in optimistic concurrency. Then go to the Properties window and change the &quot;Update Check&quot; property to Never. See below for details.</p>
<p><a href="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2009/04/image1.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2009/04/image-thumb1.png" width="691" height="446" /></a> </p>
<p>Re-running the LINQ to SQL code shown above will now yield much smaller SQL, <strong>at the cost of eliminating concurrency checking</strong>.</p>
<div style="font-family: courier new; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">UPDATE </span>[dbo].[Products]</p>
<p style="margin: 0px"><span style="color: blue">SET </span>[UnitsInStock] = @p1, [UnitsOnOrder] = @p2</p>
<p style="margin: 0px"><span style="color: blue">WHERE </span>[ProductID] = @p0</p>
<p style="margin: 0px"><span style="color: green">&#8211; @p0: Input Int (Size = 0; Prec = 0; Scale = 0) [1]</span></p>
<p style="margin: 0px"><span style="color: green">&#8211; @p1: Input SmallInt (Size = 0; Prec = 0; Scale = 0) [14]</span></p>
<p style="margin: 0px"><span style="color: green">&#8211; @p2: Input SmallInt (Size = 0; Prec = 0; Scale = 0) [100]</span></p>
<p style="margin: 0px"><span style="color: green">&#8211; Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1</span></p>
</p></div>
<p>&#160;</p>
<p>You may notice another property in the property grid called &quot;Time Stamp.&quot; If you have a timestamp column in your table, and its Time Stamp property is set to &quot;True,&quot; then Update Check on other properties will be ignored.</p>
<p>A quick summary of this information:</p>
<ol>
<li>If you have a column whose &quot;Time Stamp&quot; property is true, then only that column will be used for optimistic concurrency checking. </li>
<li>Otherwise, only columns whose &quot;Update Check&quot; property is set to &quot;Always&quot; (or &quot;WhenChanged&quot; and they <em>are</em> changed) will be used for optimistic concurrency checking. </li>
<li>Primary keys are always used as part of the WHERE clause to identify the target tuple in the database. </li>
</ol>
<h4>Attach an Entity, Change Properties, Update</h4>
<p>We can now use this overview of concurrency checking in LINQ to SQL to demonstrate the next technique, which does <em>not</em> require two round trips to the database. It is important, however, that you have all the information that LINQ to SQL needs for concurrency checking before using it.</p>
<div style="font-family: courier new; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">using</span> (<span style="color: #2b91af">NorthwindDataContext</span> db = <span style="color: blue">new</span> <span style="color: #2b91af">NorthwindDataContext</span>())</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// Create a new entity to &quot;attach&quot; to the context.</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// This means LINQ to SQL will recognize changes to</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// the entity _after_ we attach it.</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: #2b91af">Product</span> product = <span style="color: blue">new</span> <span style="color: #2b91af">Product</span>();</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// Set all properties that LINQ to SQL will use for concurrency checking.</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// Here it is just our primary key, but you will also need</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// to set values for the timestamp property (if it exists) or</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// all of the properties whose Update Check is set to &quot;Always.&quot;</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// You will also need to set values for properties whose</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// Update Check is set to &quot;When Changed,&quot; if that value has changed in this update.</span></p>
<p style="margin: 0px">&#160;&#160;&#160; product.ProductID = 1;</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// Attach the entity to the context. Now the DataContext</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// can track changes on the product variable without selecting</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// the existing Product entity from the database.</span></p>
<p style="margin: 0px">&#160;&#160;&#160; db.Products.Attach(product);</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// Change the properties. LINQ to SQL knows</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// these specific properties have changed.</span></p>
<p style="margin: 0px"><span style="color: green">&#160;&#160;&#160; // You need to ensure that these values differ from their previous value</span></p>
<p style="margin: 0px"><span style="color: green">&#160;&#160;&#160; // (e.g. product.UnitsInStock = 0; will not update UnitsInStock to 0.)</span></p>
<p style="margin: 0px">&#160;&#160;&#160; product.UnitsInStock = 14;</p>
<p style="margin: 0px">&#160;&#160;&#160; product.UnitsOnOrder = 100;</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// Flush the changes.</span></p>
<p style="margin: 0px">&#160;&#160;&#160; db.SubmitChanges();</p>
<p style="margin: 0px">}</p>
</p></div>
<p>&#160;</p>
<p>It&#8217;s the same basic pattern as before, but instead of allowing the DataContext to retrieve the Product entity from the database, we put it there ourselves with the Attach method. <strong id="attach-beware">You have to be very careful with Attach and default values. </strong>If I changed the code to set product.UnitsInStock to 0 instead of 14, the update wouldn&#8217;t occur because there would be no property change. Before the Attach, product.UnitsInStock is 0 (the default value for an Int32); before SubmitChanges, product.UnitsInStock is still 0. There was no change to the value, and thus there will be no update of the UnitsInStock column when SubmitChanges is called. To get around this you can try using one of the two other overloads for Attach. The first overload is useful for when you have both the old entity and the new entity. The code below shows how this works.</p>
<div style="font-family: courier new; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">using</span> (<span style="color: #2b91af">NorthwindDataContext</span> db = <span style="color: blue">new</span> <span style="color: #2b91af">NorthwindDataContext</span>())</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// Create the old product. You can imagine a UI tier</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// creating this instance and rehydrating all of the &quot;old&quot;</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// values before sending this to the data layer. Again,</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// the only properties that you need to set are those</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// that participate in optimistic concurrency. So, for</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// example, if ProductName&#8217;s Update Check was set to &quot;Always,&quot;</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// I would need to set that here.</span></p>
<p style="margin: 0px"><span style="color: green">&#160;&#160;&#160; //</span></p>
<p style="margin: 0px"><span style="color: green">&#160;&#160;&#160; // However, if you don&#8217;t set every property that you are updating,</span></p>
<p style="margin: 0px"><span style="color: green">&#160;&#160;&#160; // you cannot be sure that your updates will go through. For example,</span></p>
<p style="margin: 0px"><span style="color: green">&#160;&#160;&#160; // if oldProduct.UnitsInStock were 15 (in the database) but unset (i.e. 0)</span></p>
<p style="margin: 0px"><span style="color: green">&#160;&#160;&#160; // in the code below, and newProduct.UnitsInStock were 0, then LINQ to SQL</span></p>
<p style="margin: 0px"><span style="color: green">&#160;&#160;&#160; // will not update the UnitsInStock column.</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: #2b91af">Product</span> oldProduct = <span style="color: blue">new</span> <span style="color: #2b91af">Product</span></p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; ProductID = 1</p>
<p style="margin: 0px">&#160;&#160;&#160; };</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: #2b91af">Product</span> newProduct = <span style="color: blue">new</span> <span style="color: #2b91af">Product</span></p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; ProductID = 1,</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; UnitsInStock = 14,</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; UnitsOnOrder = 100</p>
<p style="margin: 0px">&#160;&#160;&#160; };</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; db.Products.Attach(newProduct, oldProduct);</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// Flush the changes.</span></p>
<p style="margin: 0px">&#160;&#160;&#160; db.SubmitChanges();</p>
<p style="margin: 0px">}</p>
</p></div>
<p>&#160;</p>
<p>When <a href="http://msdn.microsoft.com/en-us/library/bb548972.aspx">Attach(entity, original)</a> executes, LINQ to SQL sees what properties have different values between the original entity and the current entity and uses them to update the tuple in the database when SubmitChanges is called. Again, it&#8217;s critical that the original entity (oldProduct, in this example) has all of its properties that participate in optimistic concurrency set to the values that were originally retrieved from the database.</p>
<p>You can use the third overload of the Attach when no properties participate in optimistic concurrency <strong>or</strong> the only property that does represents a timestamp column. If the latter is true, then the timestamp property&#8217;s value <strong>must match</strong> the value in the database for the update to be successful. This Attach overload also tells LINQ to SQL that <em>every </em>property has changed on the entity. This gets around the problems posed by the previous two Attach overloads, but you must now make sure that you set every property; otherwise, the unset properties will be set to NULL or the appropriate default value for the type as part of the update.</p>
<div style="font-family: courier new; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">using</span> (<span style="color: #2b91af">NorthwindDataContext</span> db = <span style="color: blue">new</span> <span style="color: #2b91af">NorthwindDataContext</span>())</p>
<p style="margin: 0px">{</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// No need to create the old product anymore, because</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// the only property that participates in optimistic concurrency</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// checking is the ProductID.</span></p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: #2b91af">Product</span> product = <span style="color: blue">new</span> <span style="color: #2b91af">Product</span></p>
<p style="margin: 0px">&#160;&#160;&#160; {</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; ProductID = 1,</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; UnitsInStock = 14,</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; UnitsOnOrder = 100</p>
<p style="margin: 0px">&#160;&#160;&#160; };</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; db.Products.Attach(product, <span style="color: blue">true</span>);</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// Flush the changes. This will not do what we want!</span></p>
<p style="margin: 0px">&#160;&#160;&#160; db.SubmitChanges();</p>
<p style="margin: 0px">}</p>
</p></div>
<p>&#160;</p>
<p>The generated SQL for the code above reveals the following:</p>
<div style="font-family: courier new; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">UPDATE </span>[dbo].[Products]</p>
<p style="margin: 0px"><span style="color: blue">SET </span>[ProductName] = @p1, [SupplierID] = @p2, [CategoryID] = @p3,</p>
<p style="margin: 0px">[QuantityPerUnit] = @p4, [UnitPrice] = @p5, [UnitsInStock] = @p6,</p>
<p style="margin: 0px">[UnitsOnOrder] = @p7, [ReorderLevel] = @p8, [Discontinued] = @p9</p>
<p style="margin: 0px"><span style="color: blue">WHERE </span>[ProductID] = @p0</p>
<p style="margin: 0px"><span style="color: green">&#8211; @p0: Input Int (Size = 0; Prec = 0; Scale = 0) [1]</span></p>
<p style="margin: 0px"><span style="color: green">&#8211; @p1: Input NVarChar (Size = 0; Prec = 0; Scale = 0) [Null]</span></p>
<p style="margin: 0px"><span style="color: green">&#8211; @p2: Input Int (Size = 0; Prec = 0; Scale = 0) [Null]</span></p>
<p style="margin: 0px"><span style="color: green">&#8211; @p3: Input Int (Size = 0; Prec = 0; Scale = 0) [Null]</span></p>
<p style="margin: 0px"><span style="color: green">&#8211; @p4: Input NVarChar (Size = 0; Prec = 0; Scale = 0) [Null]</span></p>
<p style="margin: 0px"><span style="color: green">&#8211; @p5: Input Money (Size = 0; Prec = 19; Scale = 4) [Null]</span></p>
<p style="margin: 0px"><span style="color: green">&#8211; @p6: Input SmallInt (Size = 0; Prec = 0; Scale = 0) [14]</span></p>
<p style="margin: 0px"><span style="color: green">&#8211; @p7: Input SmallInt (Size = 0; Prec = 0; Scale = 0) [100]</span></p>
<p style="margin: 0px"><span style="color: green">&#8211; @p8: Input SmallInt (Size = 0; Prec = 0; Scale = 0) [Null]</span></p>
<p style="margin: 0px"><span style="color: green">&#8211; @p9: Input Bit (Size = 0; Prec = 0; Scale = 0) [False]</span></p>
<p style="margin: 0px"><span style="color: green">&#8211; Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1</span></p>
</p></div>
<p>&#160;</p>
<p>In this case it&#8217;s actually more difficult to apply only the changes we want, and we might as well use one of the other Attach overloads. Also, you should note that there is functionally no difference between <a href="http://msdn.microsoft.com/en-us/library/bb300517.aspx">Attach(entity)</a> and <a href="http://msdn.microsoft.com/en-us/library/bb548778.aspx">Attach(entity, false)</a>.</p>
<h3>Bringing It All Together</h3>
<p>Now you know what your requirements dictate for updates as well as the factors involved in updating records with LINQ to SQL, we need to bring all this information together. Remember those questions I asked in the beginning? Here they are again just in case.</p>
<ol>
<li><strong>Can multiple clients update the same database record at the same time?</strong> </li>
<li><strong>If this can happen, what data is saved when multiple simultaneous updates occur?</strong> </li>
</ol>
<p>If multiple clients can&#8217;t update the record simultaneously, then you can use any of the options that I discussed in the previous section and not worry about optimistic concurrency. The &quot;best&quot; choice depends on your scenario. For example, if you have a smart client with a DataContext that is <a href="http://blogs.msdn.com/dinesh.kulkarni/archive/2008/04/27/lifetime-of-a-linq-to-sql-datacontext.aspx">long-lived</a>, then you may not even need to worry about which scenario you use. The DataContext will track the changes to the object on the UI and then you can call SubmitChanges immediately the code reaches your data layer. But if your DataContext is short-lived, then Attach(entity, true) may be useful if you retrieve the entity from one context and update it with another. In stateless environments (like ASP.NET), Attach(entity) and retrieving the entity from the database to update are probably the easier options. But beware the <a href="#attach-beware">caveat</a> with Attach!</p>
<p>If multiple clients can update the same record simultaneously, you will need to carefully consider which data can be safely overwritten and which cannot. You can then configure LINQ to SQL to recognize your choices with the &quot;Update Check&quot; property in the DBML designer. Attach is then probably the better option, because if your optimistic concurrency checks fail, then a ChangeConflictException is thrown to alert you. If you retrieve the entity from the database and then update its properties, you must explicitly check for concurrency violations. Otherwise, the risk is always present that you overwrite data that you don&#8217;t want to.</p>
<p>In this post I haven&#8217;t discussed how to resolve conflicts when LINQ to SQL throws a ChangeConflictException. There are a lot of useful links located <a href="http://msdn.microsoft.com/en-us/library/bb399389.aspx">here</a> that do just that, in particular the three last how-tos: how to resolve concurrency conflicts <a href="http://msdn.microsoft.com/en-us/library/bb399354.aspx">by retaining database values</a>, <a href="http://msdn.microsoft.com/en-us/library/bb399421.aspx">by overwriting database values</a>, and <a href="http://msdn.microsoft.com/en-us/library/bb386918.aspx">by merging with database values</a>.</p>
<p>I hope this has been a useful source of information on updates in LINQ to SQL. Of course, this covers only the APIs themselves and doesn&#8217;t discuss how you would integrate this into, for example, an <em>n</em>-tier ASP.NET application. This is something I&#8217;m definitely interested in doing for a future post.</p>
<p><strong>EDIT:</strong> I made a few changes to this post to make a possible <a href="#attach-beware">pitfall</a> with Attach more explicit. You should definitely consider this before choosing an update strategy. Thanks to <a href="http://damieng.com/">Damien Guard</a> for pointing this out.</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.rev-net.com/ddewinter/2009/04/07/linq-to-sql-updating-entities/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Data Access Confusion/Pain</title>
		<link>http://blogs.rev-net.com/ddewinter/2009/03/29/data-access-confusionpain/</link>
		<comments>http://blogs.rev-net.com/ddewinter/2009/03/29/data-access-confusionpain/#comments</comments>
		<pubDate>Sun, 29 Mar 2009 21:08:24 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[LINQ to SQL]]></category>
		<category><![CDATA[confusion]]></category>
		<category><![CDATA[dlinq]]></category>
		<category><![CDATA[elinq]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[pain points]]></category>
		<category><![CDATA[scenarios]]></category>
		<category><![CDATA[use cases]]></category>

		<guid isPermaLink="false">http://blogs.rev-net.com/ddewinter/2009/03/29/data-access-confusionpain/</guid>
		<description><![CDATA[I recently had an idea to retarget my blogging efforts to address confusing/little-known scenarios and pain points with LINQ to SQL and the Entity Framework. Since I&#8217;m using these technologies just about all the time now I have noticed that there is no end to the amount of discussion they bring up—from high-level architectural concerns [...]]]></description>
			<content:encoded><![CDATA[<p>I recently had an idea to retarget my blogging efforts to address confusing/little-known scenarios and pain points with LINQ to SQL and the Entity Framework. Since I&#8217;m using these technologies just about all the time now I have noticed that there is no end to the amount of discussion they bring up—from high-level architectural concerns like supporting n-tier and IoC to low-level implementation-specific questions like how to use the Attach family of methods in both technologies.</p>
<p>I&#8217;m going to prioritize my posts based on feedback I get personally (from here and other sources) and what I see on Twitter; <a href="http://blog.huagati.com/res/">KristoferA</a> challenged twitterers (is that right?) to tweet their pains with both technologies with #linqtosqlpain and #efpain. I certainly have a few of my own that I want to address too.</p>
<p>(And yes, I have <a href="http://twitter.com/ddewinter/">joined</a> Twitter, too!)</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.rev-net.com/ddewinter/2009/03/29/data-access-confusionpain/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting Return Metadata from Stored Procedures</title>
		<link>http://blogs.rev-net.com/ddewinter/2008/11/09/getting-return-metadata-from-stored-procedures/</link>
		<comments>http://blogs.rev-net.com/ddewinter/2008/11/09/getting-return-metadata-from-stored-procedures/#comments</comments>
		<pubDate>Sun, 09 Nov 2008 18:11:04 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[LINQ to SQL]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[FMTONLY]]></category>
		<category><![CDATA[metadata]]></category>
		<category><![CDATA[return]]></category>
		<category><![CDATA[return value]]></category>
		<category><![CDATA[SET FMTONLY]]></category>
		<category><![CDATA[Sproc]]></category>
		<category><![CDATA[Stored Procedure]]></category>

		<guid isPermaLink="false">http://blogs.rev-net.com/ddewinter/2008/11/09/getting-return-metadata-from-stored-procedures/</guid>
		<description><![CDATA[As many of you (should) know, you can select result sets from stored procedures to return them to your application, but there is no built-in metadata that tells you the specifications of the columns in each result set. However, I was always intrigued by the way the LINQ to SQL designer managed to determine, without [...]]]></description>
			<content:encoded><![CDATA[<p>As many of you (should) know, you can select result sets from stored procedures to return them to your application, but there is no built-in metadata that tells you the specifications of the columns in each result set. However, I was always intrigued by the way the LINQ to SQL designer managed to determine, without flaw, the names, data types, etc. of the columns returned by stored procedures.</p>
<p>So to satisfy my curiosity I set up a trace using the SQL Server profiler against the database on my box and played with the LINQ to SQL designer to get it to find that metadata. Much to my surprise, it calls the stored procedure directly, passing NULL for each of its parameters.</p>
<p>Wait a minute; my stored procedure does validation, so it will raise an error when <em>xyz</em> parameter is NULL. I then noticed earlier in the trace a strange statement that involved the SET FMTONLY statement. Searching for that statement revealed <a href="http://msdn.microsoft.com/en-us/library/ms173839.aspx">this gem</a>.</p>
<p>&quot;Returns only metadata to the client. Can be used to test the format of the response without actually running the query.&quot;</p>
<p>Running something like this would then yield the metadata of the result set(s), regardless of whether errors are raised.</p>
<div style="font-size: 10pt; background: white; color: black; font-family: courier new">
<p style="margin: 0px"><span style="color: blue">SET FMTONLY ON</span>;</p>
<p style="margin: 0px"><span style="color: blue">EXEC </span>dbo.MyTestSproc @param1 = <span style="color: blue">NULL</span>, @param2 = <span style="color: blue">NULL</span>, @param3 = <span style="color: blue">NULL</span></p>
<p style="margin: 0px"><span style="color: blue">SET FMTONLY OFF</span>;</p>
</p></div>
<p>The nice thing is that you can do this for any query, not just stored procedure executions.</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.rev-net.com/ddewinter/2008/11/09/getting-return-metadata-from-stored-procedures/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>DBML Fixup Preview</title>
		<link>http://blogs.rev-net.com/ddewinter/2008/08/24/dbml-fixup-preview/</link>
		<comments>http://blogs.rev-net.com/ddewinter/2008/08/24/dbml-fixup-preview/#comments</comments>
		<pubDate>Mon, 25 Aug 2008 03:41:44 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[DBML Fixup]]></category>
		<category><![CDATA[LINQ to SQL]]></category>
		<category><![CDATA[VSX]]></category>
		<category><![CDATA[Visual Studio 2008]]></category>
		<category><![CDATA[DBML]]></category>
		<category><![CDATA[DBML Sync]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[LINQ to SQL Designer]]></category>
		<category><![CDATA[Schema Sync]]></category>
		<category><![CDATA[Visual Studio]]></category>

		<guid isPermaLink="false">http://blogs.rev-net.com/ddewinter/2008/08/24/dbml-fixup-preview/</guid>
		<description><![CDATA[Back in February I blogged about DBML Fixup&#8212;a tool whose goal was to sync LINQ to SQL models with their respective database schemas from within the Visual Studio environment, as well as to handle running various fixup tasks on models. Now it&#8217;s six months later, and I have a much clearer vision of what the [...]]]></description>
			<content:encoded><![CDATA[<p>Back in <a href="http://blogs.rev-net.com/ddewinter/2008/02/16/linq-to-sql-and-database-schema-sync/">February</a> I blogged about DBML Fixup&#8212;a tool whose goal was to sync LINQ to SQL models with their respective database schemas from within the Visual Studio environment, as well as to handle running various fixup tasks on models. Now it&#8217;s six months later, and I have a much clearer vision of what the tool is meant to be as well as a firmer command on VSX. The following screencast is a preview of the features of DBML Fixup.</p>
<p>&#160;</p>
<div id="media"><object id="csSWF" codebase="http://active.macromedia.com/flash7/cabs/ swflash.cab#version=9,0,28,0" height="498" width="640" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"><param name="_cx" value="16933"><param name="_cy" value="13176"><param name="FlashVars" value=""><param name="Movie" value="http://blogs.rev-net.com/ddewinter/wp-content/screencasts/dbmlfixup/DBMLFixupAug08.swf"><param name="Src" value="http://blogs.rev-net.com/ddewinter/wp-content/screencasts/dbmlfixup/DBMLFixupAug08.swf"><param name="WMode" value="Window"><param name="Play" value="0"><param name="Loop" value="-1"><param name="Quality" value="High"><param name="SAlign" value=""><param name="Menu" value="-1"><param name="Base" value=""><param name="AllowScriptAccess" value="always"><param name="Scale" value="ShowAll"><param name="DeviceFont" value="0"><param name="EmbedMovie" value="0"><param name="BGColor" value="1A1A1A"><param name="SWRemote" value=""><param name="MovieData" value=""><param name="SeamlessTabbing" value="1"><param name="Profile" value="0"><param name="ProfileAddress" value=""><param name="ProfilePort" value="0"><param name="AllowNetworking" value="all"><param name="AllowFullScreen" value="true"><embed name="csSWF" src="http://blogs.rev-net.com/ddewinter/wp-content/screencasts/dbmlfixup/DBMLFixupAug08.swf" width="640" height="498" bgcolor="#1a1a1a" quality="best" allowscriptaccess="always" allowfullscreen="true" scale="showall" flashvars="autostart=false" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash"></embed></object></div>
<p>&#160;</p>
<p>Here are some previous posts which (briefly) describe the domain:</p>
<p><a title="http://blogs.rev-net.com/ddewinter/2008/02/16/the-linq-to-sql-model/" href="http://blogs.rev-net.com/ddewinter/2008/02/16/the-linq-to-sql-model/">http://blogs.rev-net.com/ddewinter/2008/02/16/the-linq-to-sql-model/</a></p>
<p><a title="http://blogs.rev-net.com/ddewinter/2008/02/16/linq-to-sql-and-database-schema-sync/" href="http://blogs.rev-net.com/ddewinter/2008/02/16/linq-to-sql-and-database-schema-sync/">http://blogs.rev-net.com/ddewinter/2008/02/16/linq-to-sql-and-database-schema-sync/</a></p>
<p>&#160;</p>
<p>Any ideas about directions for the tool? Or maybe something that wasn&#8217;t covered in the screencast? I&#8217;d love to hear your ideas.</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.rev-net.com/ddewinter/2008/08/24/dbml-fixup-preview/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>The LINQ to SQL Metamodel</title>
		<link>http://blogs.rev-net.com/ddewinter/2008/02/16/the-linq-to-sql-model/</link>
		<comments>http://blogs.rev-net.com/ddewinter/2008/02/16/the-linq-to-sql-model/#comments</comments>
		<pubDate>Sat, 16 Feb 2008 23:08:56 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[DBML Fixup]]></category>
		<category><![CDATA[LINQ to SQL]]></category>
		<category><![CDATA[ORM]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[Metamodel]]></category>
		<category><![CDATA[Model]]></category>
		<category><![CDATA[NORMA]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[to]]></category>

		<guid isPermaLink="false">http://dev.rev-net.com/blog/ddewinter/?p=42</guid>
		<description><![CDATA[For my DBML Fixup project, I&#8217;ve really had to drill into the structure of LINQ to SQL&#8212;including how the data is stored in the .dbml file, how various changes in the designer affect the serialized XML (which is the format of the .dbml file), and what the various elements and attributes in the DBML file [...]]]></description>
			<content:encoded><![CDATA[<p>For my <a href="http://blogs.rev-net.com/ddewinter/?p=41">DBML Fixup project</a>, I&#8217;ve really had to drill into the structure of LINQ to SQL&#8212;including how the data is stored in the .dbml file, how various changes in the designer affect the serialized XML (which is the format of the .dbml file), and what the various elements and attributes in the DBML file actually mean. (Honestly, what does the IsForeignKey attribute on the Association element imply as its meaning? I thought all &quot;associations&quot; represented foreign keys!)</p>
<p>At first I tried to dissect LINQ to SQL by keeping track of the various elements and attributes and their representations in the XML and the designer in big Excel tables. They quickly became unwieldy, and I decided to cut my losses and model the LINQ to SQL schema (DBMLSchema.xsd). Needless to say this was a very challenging exercise, but I gleaned a significant amount of knowledge about LINQ to SQL after finishing it.</p>
<p>The purpose of this post is to post the various pages of the LINQ to SQL model; I want this post to clarify the infrastructure of LINQ to SQL to others, so I would appreciate if you can comment on any inconsistencies or missing constraints you can see. I used Object-Role Modeling (<a href="http://msdn2.microsoft.com/en-us/library/aa290383(VS.71).aspx">ORM</a>) for the model, so if you are not familiar with that, you may want to check out the following resources:</p>
<ol>
<li>Object Role Modeling: An Overview, <a href="http://msdn2.microsoft.com/en-us/library/aa290383(VS.71).aspx">http://msdn2.microsoft.com/en-us/library/aa290383(VS.71).aspx</a> </li>
<li>Halpin, T. 2001. <em>Information Modeling and Relational Databases: From Conceptual Analysis to Logical Design</em>.San Francisco: Morgan Kaufmann Publishers </li>
</ol>
<p>The model starts like this&#8230;here&#8217;s the database page. The derivation rules aren&#8217;t on the diagram explicitly, as they are stored as part of the properties of the fact type. Other advantages of having the .orm file are that I&#8217;ve put definitions on all of the fact types to clarify their meaning, in the case that the predicate text is still not clear enough. If anyone wants the .orm file, feel free to contact me at david.dewinter AT (@) rev-net DOT (.) com. (You can open .orm files with Visual Studio after installing <a href="http://sourceforge.net/projects/orm">Project NORMA</a>.) I will also put up a contact form soon&#8230; </p>
<p> <span id="more-83"></span><img alt="database.jpg" src="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2008/02/database.jpg" />
</p>
<p><strong>Figure 1. The Database element.</strong></p>
<p><img alt="connectiondetails.jpg" src="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2008/02/connectiondetails.jpg" /></p>
<p><strong>Figure 2. The Connection element (renamed ConnectionDetails for clarity).</strong></p>
<p><img alt="table.jpg" src="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2008/02/table.jpg" /></p>
<p><strong>Figure 3. The Table and Type elements.</strong></p>
<p><img alt="column.jpg" src="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2008/02/column.jpg" /></p>
<p><strong>Figure 4. The Column element.</strong></p>
<p><img alt="associationend.jpg" src="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2008/02/associationend.jpg" /></p>
<p><strong>Figure 5. The Assocation element (renamed AssocationEnd for clarity).</strong></p>
<p><img alt="function.jpg" src="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2008/02/function.jpg" /></p>
<p><strong>Function 6. The Function element.</strong></p>
<p><img alt="tablefunction.jpg" src="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2008/02/tablefunction.jpg" /></p>
<p><strong>Figure 7. The TableFunction element.</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.rev-net.com/ddewinter/2008/02/16/the-linq-to-sql-model/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>LINQ to SQL and Database Schema Sync</title>
		<link>http://blogs.rev-net.com/ddewinter/2008/02/16/linq-to-sql-and-database-schema-sync/</link>
		<comments>http://blogs.rev-net.com/ddewinter/2008/02/16/linq-to-sql-and-database-schema-sync/#comments</comments>
		<pubDate>Sat, 16 Feb 2008 22:09:25 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[DBML Fixup]]></category>
		<category><![CDATA[LINQ to SQL]]></category>
		<category><![CDATA[Requirements Analysis]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[Requirements]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[to]]></category>

		<guid isPermaLink="false">http://dev.rev-net.com/blog/ddewinter/?p=41</guid>
		<description><![CDATA[Since the new year I&#8217;ve been working on a project that attempts to solve the following problem:
How do I keep my generated entity classes in sync with the current database schema using LINQ to SQL?
For  some people, this question is moot. It&#8217;s easy enough to utilize the current &#8220;resync&#8221; mechanism in LINQ to SQL [...]]]></description>
			<content:encoded><![CDATA[<p>Since the new year I&#8217;ve been working on a project that attempts to solve the following problem:</p>
<p><em>How do I keep my generated entity classes in sync with the current database schema using LINQ to SQL?</em></p>
<p>For  some people, this question is moot. It&#8217;s easy enough to utilize the current &#8220;resync&#8221; mechanism in LINQ to SQL by deleting all the entity classes and functions (the LINQ to SQL term for sprocs and UDFs) on the designer surface and then redragging and dropping the tables and functions of interest, thus updating the entity classes by regenerating from scratch. However, for others, this solution is not good enough for a few reasons:</p>
<p><span id="more-82"></span></p>
<ol>
<li>In the organizations I&#8217;ve been in, column names are camel case, and .NET property names are Pascal case. When creating the entity classes, I have to fix the casing of all the properties since their names default to the names of the columns. Using the solution above, I would have to repeat this process every time the database schema changed!</li>
<li>If developers prefix their table and column names with &#8220;tbl_&#8221;, &#8220;int_&#8221;, &#8220;str_&#8221;, &#8220;usp_&#8221;, etc. but have different standards in .NET code, then they have to change the generated entity class and property names every time the database schema changes.</li>
<li>There are quite a few properties that a developer can set in the .dbml (LINQ to SQL) file that cannot be set in the designer. Every time one of those properties is set, it exposes a risk in that they have to be reset every time the database object on which that property was set changes.</li>
<li>Not even considering name changes (which are understandably trivial to some people), what about inheritance relationships? The designer can&#8217;t infer when a table maps to a class hierarchy (<a href="http://www.code-magazine.com/article.aspx?quickid=990712062&amp;page=2">table-per-hierarchy, or TPH</a>). Every inheritance relationship has to be remapped when the database is changed.</li>
</ol>
<p>And the list goes on&#8230;</p>
<p>As you can see, all of these customizations can become quite expensive over time if a database changes often. Perhaps some developers have taken it upon themselves to write their own scripts to keep their customizations in the .dbml file for a single database, which is great, but not scalable. I believe something that the community could benefit greatly from is a tool that tracks customizations to the file and allows them to restored after the designer re-generates the entity classes and functions. Perhaps something that could manage the entire resync process for you would be even better.</p>
<p>At this point I am fishing for requirements, more specifically common tweaks that developers want to make to the LINQ to SQL files. The common tweaks I have identified so far are (1) to transform property names to be Pascal case, (2) to remove prefixes from the names of database objects, and (3) to automate mapping the types of columns to various (developer-defined) enumerations.</p>
<p>Any input you guys can give would be appreciated! I&#8217;ll be posting more on this tool in the future. Currently its name is &#8220;DBML Fixup,&#8221; but if you have any better alternatives feel free to share.</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.rev-net.com/ddewinter/2008/02/16/linq-to-sql-and-database-schema-sync/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
	</channel>
</rss>
