<?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>Technical Jargon &#187; ASP.NET MVC</title>
	<atom:link href="http://www.jeremyskinner.co.uk/category/aspnet-mvc/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.jeremyskinner.co.uk</link>
	<description>On Error Resume Coding</description>
	<lastBuildDate>Sun, 08 Aug 2010 13:36:41 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>MvcContrib Grid Part 7 &#8211; Auto-generated columns</title>
		<link>http://www.jeremyskinner.co.uk/2010/04/27/mvccontrib-grid-part-7-auto-generated-columns/</link>
		<comments>http://www.jeremyskinner.co.uk/2010/04/27/mvccontrib-grid-part-7-auto-generated-columns/#comments</comments>
		<pubDate>Tue, 27 Apr 2010 09:18:39 +0000</pubDate>
		<dc:creator>Jeremy Skinner</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[mvccontrib]]></category>

		<guid isPermaLink="false">http://www.jeremyskinner.co.uk/2010/04/27/mvccontrib-grid-part-7-auto-generated-columns/</guid>
		<description><![CDATA[This is part 7 of a series of posts on the MvcContrib grid component. Part 1 – Introduction Part 2 – New Syntax Part 3 – GridModels and GridRenderes Part 4 – Limitations of the WebFormsViewEngine Part 5 – The Action Syntax Part 6 – Sorting Part 7 – Auto-generated columns The MvcContrib grid provides [...]]]></description>
			<content:encoded><![CDATA[<p>This is part 7 of a series of posts on the <a href="http://mvccontrib.codeplex.com/wikipage?title=Grid">MvcContrib grid component</a>.</p>
<ul>
<li><a href="http://www.jeremyskinner.co.uk/2009/02/08/rewriting-the-mvccontrib-grid/">Part 1 – Introduction</a> </li>
<li><a href="http://www.jeremyskinner.co.uk/2009/02/22/rewriting-the-mvccontrib-grid-part-2-new-syntax/">Part 2 – New Syntax</a> </li>
<li><a href="http://www.jeremyskinner.co.uk/2009/02/23/rewriting-the-mvccontrib-grid-part-3-gridmodels-and-gridrenderers">Part 3 – GridModels and GridRenderes</a> </li>
<li><a href="http://www.jeremyskinner.co.uk/2009/02/28/mvccontrib-grid-part-4-limitations-of-the-webformsviewengine">Part 4 – Limitations of the WebFormsViewEngine</a> </li>
<li><a href="http://www.jeremyskinner.co.uk/2009/03/01/mvccontrib-grid-part-5-the-action-syntax">Part 5 – The Action Syntax</a> </li>
<li><a href="http://www.jeremyskinner.co.uk/2010/03/14/mvccontrib-grid-part-6-sorting/">Part 6 – Sorting</a> </li>
<li><a href="http://www.jeremyskinner.co.uk/2010/04/27/mvccontrib-grid-part-7-auto-generated-columns/">Part 7 – Auto-generated columns</a></li>
</ul>
<p>The MvcContrib grid provides a way to automatically generate columns based on the public properties of an object. This is particularly useful when you are using a dedicated <a href="http://martinfowler.com/eaaDev/PresentationModel.html">presentation model</a> where the object properties map directly to the columns that you want to display. </p>
<p>To make use of this feature, you can call the <strong>AutoGenerateColumns</strong> method in the Grid declaration:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:4318B029-7F5A-4155-A9CF-329C469B73B3:b51d0d81-c85d-4f64-ae16-23cde9daa90f" class="wlWriterEditableSmartContent">

<div class="wp_syntax"><div class="code"><pre class="asp" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;%</span><span style="color: #006600; font-weight: bold;">=</span> Html.<span style="color: #9900cc;">Grid</span><span style="color: #006600; font-weight:bold;">&#40;</span>Model<span style="color: #006600; font-weight:bold;">&#41;</span>.<span style="color: #9900cc;">AutoGenerateColumns</span><span style="color: #006600; font-weight:bold;">&#40;</span><span style="color: #006600; font-weight:bold;">&#41;</span> <span style="color: #000000; font-weight: bold;">%&gt;</span></pre></div></div>

</div>
<p>By default, this will generate one column per public property and the name of the property will be used as the column heading (although PascalCased properties will have spaces inserted, eg “DateOfBirth” would be rendered as “Date Of Birth”).</p>
<p>This output can be customised by making use of MVC2’s ModelMetadata.</p>
<p>Out of the box, MVC2 uses the System.ComponentModel.DataAnnotations attributes to obtain metadata about a particular type (although you can also use <a href="http://fluentvalidation.codeplex.com">other frameworks</a>). The following attributes can be used to customise the auto-generated columns:</p>
<ul>
<li>ScaffoldColumn – can be used to prevent a property from being rendered as a grid column</li>
<li>DisplayName – can be used to provide a custom column heading</li>
<li>DisplayFormat – can be used to specify a custom display format</li>
</ul>
<p>Additional columns not on your presentation model can also be added by making a call to the normal <strong>Columns</strong> method after the call to <strong>AutoGenerateColumns</strong>. For example, imagine we have a CustomerPresentationModel:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:4318B029-7F5A-4155-A9CF-329C469B73B3:86b1f7f8-b42e-49bd-aa1f-eb32a7b604bb" class="wlWriterEditableSmartContent">

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> CustomerPresentationModel <span style="color: #000000;">&#123;</span>
&nbsp;
   <span style="color: #000000;">&#91;</span>ScaffoldColumn<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">false</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
   <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> CustomerId <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
&nbsp;
   <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> Name <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
   <span style="color: #0600FF;">public</span> DateTime DateOfBirth <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

</div>
<p>If a collection of these objects is passed to the Grid method, then two columns will be auto-generated – one for Name and one for DateOfBirth (CustomerId is excluded because it is decorated with ScaffoldColumn(false))</p>
<p>If we also want to add an “Edit” link for the customer, then we could add an additional column:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:4318B029-7F5A-4155-A9CF-329C469B73B3:40529881-3035-4a98-aca8-d2068d2ae5c9" class="wlWriterEditableSmartContent">

<div class="wp_syntax"><div class="code"><pre class="asp" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;%</span><span style="color: #006600; font-weight: bold;">=</span> Html.<span style="color: #9900cc;">Grid</span><span style="color: #006600; font-weight:bold;">&#40;</span>Model<span style="color: #006600; font-weight:bold;">&#41;</span>.<span style="color: #9900cc;">AutoGenerateColumns</span><span style="color: #006600; font-weight:bold;">&#40;</span><span style="color: #006600; font-weight:bold;">&#41;</span>.<span style="color: #9900cc;">Columns</span><span style="color: #006600; font-weight:bold;">&#40;</span>extraColumns <span style="color: #006600; font-weight: bold;">=&gt;</span> <span style="color: #006600; font-weight:bold;">&#123;</span>
        extraColumns.<span style="color: #990099; font-weight: bold;">For</span><span style="color: #006600; font-weight:bold;">&#40;</span>x <span style="color: #006600; font-weight: bold;">=&gt;</span> Html.<span style="color: #9900cc;">ActionLink</span><span style="color: #006600; font-weight:bold;">&#40;</span><span style="color: #cc0000;">&quot;Edit Customer&quot;</span>, <span style="color: #cc0000;">&quot;Edit&quot;</span>, <span style="color: #0000ff; font-weight: bold;">new</span><span style="color: #006600; font-weight:bold;">&#123;</span> id <span style="color: #006600; font-weight: bold;">=</span> x.<span style="color: #9900cc;">CustomerId</span> <span style="color: #006600; font-weight:bold;">&#125;</span><span style="color: #006600; font-weight:bold;">&#41;</span><span style="color: #006600; font-weight: bold;">;</span>
<span style="color: #006600; font-weight:bold;">&#125;</span><span style="color: #006600; font-weight:bold;">&#41;</span> <span style="color: #000000; font-weight: bold;">%&gt;</span></pre></div></div>

</div>
<p>The additional column contains a link to the edit page for each customer. Note that while columns are automatically HTML-encoded, the grid will detect that ActionLink returns an instance of MvcHtmlString and therefore won’t encode this particular column.</p>
<p>Additional columns can also be re-ordered. For example, if we wanted our “Edit” link to appear before the Name/DateOfBirth then the <strong>InsertAt </strong>method could be used:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:4318B029-7F5A-4155-A9CF-329C469B73B3:83f8e90d-f263-4fa5-b0a1-30a607477686" class="wlWriterEditableSmartContent">

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">&lt;%=</span> Html.<span style="color: #0000FF;">Grid</span><span style="color: #000000;">&#40;</span>Model<span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">AutoGenerateColumns</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Columns</span><span style="color: #000000;">&#40;</span>extraColumns <span style="color: #008000;">=&gt;</span> <span style="color: #000000;">&#123;</span>
        extraColumns.<span style="color: #0600FF;">For</span><span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> Html.<span style="color: #0000FF;">ActionLink</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Edit Customer&quot;</span>, <span style="color: #666666;">&quot;Edit&quot;</span>, <span style="color: #008000;">new</span><span style="color: #000000;">&#123;</span> id <span style="color: #008000;">=</span> x.<span style="color: #0000FF;">CustomerId</span> <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span>
            .<span style="color: #0000FF;">InsertAt</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">%&gt;</span></pre></div></div>

</div>
<p>Note that the InsertAt method is not contained in the latest MvcContrib release – you’ll need to build from source to get this.</p>
<p>I’ve also started to put together some <a href="http://mvccontrib.codeplex.com/wikipage?title=Grid">documentation for the grid</a> on the MvcContrib wiki.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeremyskinner.co.uk/2010/04/27/mvccontrib-grid-part-7-auto-generated-columns/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>MvcContrib Grid Part 6 &#8211; Sorting</title>
		<link>http://www.jeremyskinner.co.uk/2010/03/14/mvccontrib-grid-part-6-sorting/</link>
		<comments>http://www.jeremyskinner.co.uk/2010/03/14/mvccontrib-grid-part-6-sorting/#comments</comments>
		<pubDate>Sun, 14 Mar 2010 13:48:00 +0000</pubDate>
		<dc:creator>Jeremy Skinner</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[mvccontrib]]></category>

		<guid isPermaLink="false">http://www.jeremyskinner.co.uk/2010/03/14/mvccontrib-grid-part-6-sorting/</guid>
		<description><![CDATA[This is part 6 of a series about the MvcContrib Grid. Part 1 – Introduction Part 2 – New Syntax Part 3 – GridModels and GridRenderes Part 4 – Limitations of the WebFormsViewEngine Part 5 – The Action Syntax Part 6 – Sorting Part 7 – Auto-generated columns I recently added single-column sorting support to [...]]]></description>
			<content:encoded><![CDATA[<p>This is part 6 of a series about the MvcContrib Grid.</p>
<ul>
<li><a href="http://www.jeremyskinner.co.uk/2009/02/08/rewriting-the-mvccontrib-grid/">Part 1 – Introduction</a> </li>
<li><a href="http://www.jeremyskinner.co.uk/2009/02/22/rewriting-the-mvccontrib-grid-part-2-new-syntax/">Part 2 – New Syntax</a> </li>
<li><a href="http://www.jeremyskinner.co.uk/2009/02/23/rewriting-the-mvccontrib-grid-part-3-gridmodels-and-gridrenderers">Part 3 – GridModels and GridRenderes</a> </li>
<li><a href="http://www.jeremyskinner.co.uk/2009/02/28/mvccontrib-grid-part-4-limitations-of-the-webformsviewengine">Part 4 – Limitations of the WebFormsViewEngine</a> </li>
<li><a href="http://www.jeremyskinner.co.uk/2009/03/01/mvccontrib-grid-part-5-the-action-syntax">Part 5 – The Action Syntax</a> </li>
<li><a href="http://www.jeremyskinner.co.uk/2010/03/14/mvccontrib-grid-part-6-sorting/">Part 6 – Sorting</a> </li>
<li><a href="http://www.jeremyskinner.co.uk/2010/04/27/mvccontrib-grid-part-7-auto-generated-columns/">Part 7 – Auto-generated columns</a> </li>
</ul>
<p>I recently added single-column sorting support to the MvcContrib grid. This can be turned on by calling the “Sort” method on a grid declaration and accepting a parameter of type GridSortOptions in your controller actions.</p>
<p>Controller:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:4318B029-7F5A-4155-A9CF-329C469B73B3:92bcd9ca-e271-4b4b-a97e-1f2912870984" class="wlWriterEditableSmartContent">

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> ActionResult Sorting<span style="color: #000000;">&#40;</span>GridSortOptions sort<span style="color: #000000;">&#41;</span> 
<span style="color: #000000;">&#123;</span>
  ViewData<span style="color: #000000;">&#91;</span><span style="color: #666666;">&quot;sort&quot;</span><span style="color: #000000;">&#93;</span> <span style="color: #008000;">=</span> sort<span style="color: #008000;">;</span>
  var people <span style="color: #008000;">=</span> _peopleFactory.<span style="color: #0000FF;">CreatePeople</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
  <span style="color: #0600FF;">if</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">!</span><span style="color: #FF0000;">string</span>.<span style="color: #0000FF;">IsNullOrEmpty</span><span style="color: #000000;">&#40;</span>sort.<span style="color: #0000FF;">Column</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
    people <span style="color: #008000;">=</span> people.<span style="color: #0000FF;">OrderBy</span><span style="color: #000000;">&#40;</span>sort.<span style="color: #0000FF;">Column</span>, sort.<span style="color: #0000FF;">Direction</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #000000;">&#125;</span>
&nbsp;
  <span style="color: #0600FF;">return</span> View<span style="color: #000000;">&#40;</span>people<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

</div>
<p>View:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:4318B029-7F5A-4155-A9CF-329C469B73B3:f60fcfee-7464-4712-a63a-ed9dcbf3c283" class="wlWriterEditableSmartContent">

<div class="wp_syntax"><div class="code"><pre class="asp" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;%</span><span style="color: #006600; font-weight: bold;">=</span> Html.<span style="color: #9900cc;">Grid</span><span style="color: #006600; font-weight:bold;">&#40;</span>Model<span style="color: #006600; font-weight:bold;">&#41;</span>
  .<span style="color: #9900cc;">Sort</span><span style="color: #006600; font-weight:bold;">&#40;</span>ViewData<span style="color: #006600; font-weight:bold;">&#91;</span><span style="color: #cc0000;">&quot;sort&quot;</span><span style="color: #006600; font-weight:bold;">&#93;</span> <span style="color: #330066;">as</span> GridSortOptions<span style="color: #006600; font-weight:bold;">&#41;</span>
  .<span style="color: #9900cc;">Columns</span><span style="color: #006600; font-weight:bold;">&#40;</span>column <span style="color: #006600; font-weight: bold;">=&gt;</span> <span style="color: #006600; font-weight:bold;">&#123;</span>
      column.<span style="color: #990099; font-weight: bold;">For</span><span style="color: #006600; font-weight:bold;">&#40;</span>x <span style="color: #006600; font-weight: bold;">=&gt;</span> x.<span style="color: #9900cc;">Id</span><span style="color: #006600; font-weight:bold;">&#41;</span>.<span style="color: #9900cc;">Named</span><span style="color: #006600; font-weight:bold;">&#40;</span><span style="color: #cc0000;">&quot;Person ID&quot;</span><span style="color: #006600; font-weight:bold;">&#41;</span><span style="color: #006600; font-weight: bold;">;</span>
      column.<span style="color: #990099; font-weight: bold;">For</span><span style="color: #006600; font-weight:bold;">&#40;</span>x <span style="color: #006600; font-weight: bold;">=&gt;</span> x.<span style="color: #9900cc;">Name</span><span style="color: #006600; font-weight:bold;">&#41;</span><span style="color: #006600; font-weight: bold;">;</span>
      column.<span style="color: #990099; font-weight: bold;">For</span><span style="color: #006600; font-weight:bold;">&#40;</span>x <span style="color: #006600; font-weight: bold;">=&gt;</span> x.<span style="color: #9900cc;">Gender</span><span style="color: #006600; font-weight:bold;">&#41;</span><span style="color: #006600; font-weight: bold;">;</span>
      column.<span style="color: #990099; font-weight: bold;">For</span><span style="color: #006600; font-weight:bold;">&#40;</span>x <span style="color: #006600; font-weight: bold;">=&gt;</span> x.<span style="color: #9900cc;">DateOfBirth</span><span style="color: #006600; font-weight:bold;">&#41;</span>.<span style="color: #9900cc;">Format</span><span style="color: #006600; font-weight:bold;">&#40;</span><span style="color: #cc0000;">&quot;{0:d}&quot;</span><span style="color: #006600; font-weight:bold;">&#41;</span><span style="color: #006600; font-weight: bold;">;</span>
    <span style="color: #006600; font-weight:bold;">&#125;</span><span style="color: #006600; font-weight:bold;">&#41;</span> <span style="color: #000000; font-weight: bold;">%&gt;</span></pre></div></div>

</div>
<p>By calling the “Sort” method, this tells the grid that sorting should be enabled. This will generate sorting links for each column heading (note that currently sorting is enabled for all columns – there is no way to enable it for individual columns only. I’ll change this in a future release)</p>
<p>These sorting links will add two additional parameters to the querystring: Column and Direction. These can be handled in your controller action by taking as a parameter an object of type GridSortOptions.</p>
<p>Using this object, you can then sort your data using whatever mechanism you choose. Out of the box, MvcContrib provides an overload for the “OrderBy” extension method that takes a property name and a direction and delegates the sorting to IQueryable. However, use of this extension method is entirely optional.</p>
<p>This also works with the grid’s paging support, so if you want your data to be both paged and sorted then you can make a call to AsPagination (or by using a custom IPagination provider) after the call to OrderBy:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:4318B029-7F5A-4155-A9CF-329C469B73B3:39a91ae4-7c05-4df8-ae53-cbc4f740b801" class="wlWriterEditableSmartContent">

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> ActionResult SortingAndPaging<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span><span style="color: #008000;">?</span> page, GridSortOptions sort<span style="color: #000000;">&#41;</span> 
<span style="color: #000000;">&#123;</span>
  ViewData<span style="color: #000000;">&#91;</span><span style="color: #666666;">&quot;sort&quot;</span><span style="color: #000000;">&#93;</span> <span style="color: #008000;">=</span> sort<span style="color: #008000;">;</span>
  var people <span style="color: #008000;">=</span> _peopleFactory.<span style="color: #0000FF;">CreatePeople</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
  <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #008000;">!</span><span style="color: #FF0000;">string</span>.<span style="color: #0000FF;">IsNullOrEmpty</span><span style="color: #000000;">&#40;</span>sort.<span style="color: #0000FF;">Column</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
    people <span style="color: #008000;">=</span> people.<span style="color: #0000FF;">OrderBy</span><span style="color: #000000;">&#40;</span>sort.<span style="color: #0000FF;">Column</span>, sort.<span style="color: #0000FF;">Direction</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #000000;">&#125;</span>
&nbsp;
  people <span style="color: #008000;">=</span> people.<span style="color: #0000FF;">AsPagination</span><span style="color: #000000;">&#40;</span>page <span style="color: #008000;">??</span> <span style="color: #FF0000;">1</span>, <span style="color: #FF0000;">10</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
  <span style="color: #0600FF;">return</span> View<span style="color: #000000;">&#40;</span>people<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

</div>
<p>…and the results will be as expected.</p>
<p>When a column is sorted, the CSS classes of “sort_asc” or “sort_desc” will be applied to the relevant &lt;th&gt; element, so you can style the column headings (for example, by adding up/down arrows).</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeremyskinner.co.uk/2010/03/14/mvccontrib-grid-part-6-sorting/feed/</wfw:commentRss>
		<slash:comments>28</slash:comments>
		</item>
		<item>
		<title>FluentValidation C4mvc Video</title>
		<link>http://www.jeremyskinner.co.uk/2010/02/13/fluentvalidation-c4mvc-video/</link>
		<comments>http://www.jeremyskinner.co.uk/2010/02/13/fluentvalidation-c4mvc-video/#comments</comments>
		<pubDate>Sat, 13 Feb 2010 20:24:37 +0000</pubDate>
		<dc:creator>Jeremy Skinner</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[FluentValidation]]></category>

		<guid isPermaLink="false">http://www.jeremyskinner.co.uk/?p=363</guid>
		<description><![CDATA[The video of my FluentValidation presentation for c4mvc is now available. In the video I cover some of the basics of using FluentValidation including: How to create a validator class Using templated error messages Writing custom validation rules Unit testing validators After this, I demonstrate how you can use FluentValidation with ASP.NET MVC2 to perform [...]]]></description>
			<content:encoded><![CDATA[<p>
The video of my FluentValidation presentation for <a href="http://www.c4mvc.net">c4mvc</a> is <a href="http://www.viddler.com/explore/c4mvc/videos/10/">now available</a>.
</p>
<p>
In the video I cover some of the basics of using FluentValidation including:
</p>
<ul>
<li>How to create a validator class</li>
<li>Using templated error messages</li>
<li>Writing custom validation rules</li>
<li>Unit testing validators</li>
</ul>
<p>
After this, I demonstrate how you can use FluentValidation with ASP.NET MVC2 to perform automatic validation when using Model Binding, clientside validation and using FluentValidation to generate metadata.
</p>
<p>
The code for the presentation <a href="http://github.com/downloads/JeremySkinner/Presentations/FluentValidation-2010-02-20.zip">can be downloaded from here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeremyskinner.co.uk/2010/02/13/fluentvalidation-c4mvc-video/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>FluentValidation 1.2 Beta 2 and MVC2 RC2</title>
		<link>http://www.jeremyskinner.co.uk/2010/02/06/fluentvalidation-1-2-beta-2-and-mvc2-rc2/</link>
		<comments>http://www.jeremyskinner.co.uk/2010/02/06/fluentvalidation-1-2-beta-2-and-mvc2-rc2/#comments</comments>
		<pubDate>Sat, 06 Feb 2010 12:03:12 +0000</pubDate>
		<dc:creator>Jeremy Skinner</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[FluentValidation]]></category>

		<guid isPermaLink="false">http://www.jeremyskinner.co.uk/?p=343</guid>
		<description><![CDATA[FluentValidation 1.2 beta 2 is now available to download. This release focuses mainly on integration with ASP.NET MVC 2. Since my post on Limitations of MVC2&#8242;s ModelValidatorProviders ASP.NET MVC2 RC2 has been released which addresses some of the issues that I raised in the post. Firstly, validation in MVC2 RC2 now performs model-validation rather than [...]]]></description>
			<content:encoded><![CDATA[<p>
FluentValidation 1.2 beta 2 <a href="http://fluentvalidation.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=40035">is now available to download</a>. This release focuses mainly on integration with ASP.NET MVC 2.
</p>
<p>
Since my post on <a href="http://www.jeremyskinner.co.uk/2010/01/13/limitations-of-mvc2s-modelvalidatorproviders/">Limitations of MVC2&#8242;s ModelValidatorProviders</a> ASP.NET MVC2 RC2 has been released which addresses some of the issues that I raised in the post.
</p>
<p>
Firstly, validation in MVC2 RC2 <a href="http://bradwilson.typepad.com/blog/2010/01/input-validation-vs-model-validation-in-aspnet-mvc.html">now performs model-validation rather than input validation</a>. This is much more in line with how FluentValidation works which makes the FluentValidation integration much more consistent with the built-in validation.
</p>
<p>
Secondly, it is now possible to disable the DataAnnotationsModelValidatorProvider&#8217;s &#8220;greedy&#8221; required rule. Out of the box, the DataAnnotationsModelValidatorProvider will *always* validate non-nullable value types, irrespective of whether the property is decorated with a [Required] attribute. This meant that you had to un-register the DataAnnotations provider if you didn&#8217;t want to get duplicate errors. It is now possible to turn this off by calling <strong>DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;</strong> in your application startup routine.
</p>
<p>
Finally, I added the ability to be able to execute some of FluentValidation&#8217;s Property Validators without needing to validate the entire object. This means it is now possible to stop the default &#8220;A value was required&#8221; message from being added to ModelState.
</p>
<h3>Enabling the FluentValidationModelValidatorProvider</h3>
<p>
After <a href="http://fluentvalidation.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=40035">downloading the 1.2 beta 2 release</a> you&#8217;ll need to add a reference to FluentValidation.dll and FluentValidation.Mvc.dll
</p>
<p>
To enable the FluentValidationModelValidatorProvider you will need to add it to the ModelValidatorProviders collection in your application startup routine:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">void</span> Application_Start<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
	RegisterRoutes<span style="color: #000000;">&#40;</span>RouteTable.<span style="color: #0000FF;">Routes</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	DataAnnotationsModelValidatorProvider
		.<span style="color: #0000FF;">AddImplicitRequiredAttributeForValueTypes</span> <span style="color: #008000;">=</span> false<span style="color: #008000;">;</span>
&nbsp;
	ModelValidatorProviders.<span style="color: #0000FF;">Providers</span>.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>
		<span style="color: #008000;">new</span> FluentValidationModelValidatorProvider<span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> AttributedValidatorFactory<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
Note that you need to pass an IValidatorFactory to the FluentValidationModelValidatorProvider so that it knows how to create your validator instances. I&#8217;m using the AttributedValidatorFactory in this example, but in a real application you would probably use an implementation that wraps an IoC container instead.
</p>
<p>
Next, you can create your model object and associated validator:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>Validator<span style="color: #000000;">&#40;</span><span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span>PersonValidator<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> Person <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> Id <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
	<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> Name <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
	<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> Email <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
	<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> Age <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> PersonValidator <span style="color: #008000;">:</span> AbstractValidator<span style="color: #008000;">&lt;</span>Person<span style="color: #008000;">&gt;</span> <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> PersonValidator<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		RuleFor<span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Id</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">NotNull</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
		RuleFor<span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Name</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Length</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">0</span>, <span style="color: #FF0000;">10</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
		RuleFor<span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Email</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">EmailAddress</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
		RuleFor<span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Age</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">InclusiveBetween</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">18</span>, <span style="color: #FF0000;">60</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
Finally, you can create the controller and associated view:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> PeopleController <span style="color: #008000;">:</span> Controller <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> ActionResult Create<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">return</span> View<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #000000;">&#91;</span>AcceptVerbs<span style="color: #000000;">&#40;</span>HttpVerbs.<span style="color: #0000FF;">Post</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
	<span style="color: #0600FF;">public</span> ActionResult Create<span style="color: #000000;">&#40;</span>Person person<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
&nbsp;
		<span style="color: #0600FF;">if</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">!</span> ModelState.<span style="color: #0000FF;">IsValid</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
			<span style="color: #0600FF;">return</span> View<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Create&quot;</span>, person<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
		<span style="color: #000000;">&#125;</span>
&nbsp;
		TempData<span style="color: #000000;">&#91;</span><span style="color: #666666;">&quot;notice&quot;</span><span style="color: #000000;">&#93;</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Person successfully created&quot;</span><span style="color: #008000;">;</span>
		<span style="color: #0600FF;">return</span> RedirectToAction<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Index&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="asp" style="font-family:monospace;">&nbsp;
<span style="color: #000000; font-weight: bold;">&lt;%</span><span style="color: #006600; font-weight: bold;">=</span> Html.<span style="color: #9900cc;">ValidationSummary</span><span style="color: #006600; font-weight:bold;">&#40;</span><span style="color: #006600; font-weight:bold;">&#41;</span> <span style="color: #000000; font-weight: bold;">%&gt;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">&lt;%</span> using <span style="color: #006600; font-weight:bold;">&#40;</span>Html.<span style="color: #9900cc;">BeginForm</span><span style="color: #006600; font-weight:bold;">&#40;</span><span style="color: #006600; font-weight:bold;">&#41;</span><span style="color: #006600; font-weight:bold;">&#41;</span> <span style="color: #006600; font-weight:bold;">&#123;</span> <span style="color: #000000; font-weight: bold;">%&gt;</span>
	Id: <span style="color: #000000; font-weight: bold;">&lt;%</span><span style="color: #006600; font-weight: bold;">=</span> Html.<span style="color: #9900cc;">TextBoxFor</span><span style="color: #006600; font-weight:bold;">&#40;</span>x <span style="color: #006600; font-weight: bold;">=&gt;</span> x.<span style="color: #9900cc;">Id</span><span style="color: #006600; font-weight:bold;">&#41;</span> <span style="color: #000000; font-weight: bold;">%&gt;</span><span style="color: #000000; font-weight: bold;">&lt;%</span><span style="color: #006600; font-weight: bold;">=</span> Html.<span style="color: #9900cc;">ValidationMessageFor</span><span style="color: #006600; font-weight:bold;">&#40;</span>x <span style="color: #006600; font-weight: bold;">=&gt;</span> x.<span style="color: #9900cc;">Id</span><span style="color: #006600; font-weight:bold;">&#41;</span> <span style="color: #000000; font-weight: bold;">%&gt;</span>
	&lt;br /&gt;
	Name: <span style="color: #000000; font-weight: bold;">&lt;%</span><span style="color: #006600; font-weight: bold;">=</span> Html.<span style="color: #9900cc;">TextBoxFor</span><span style="color: #006600; font-weight:bold;">&#40;</span>x <span style="color: #006600; font-weight: bold;">=&gt;</span> x.<span style="color: #9900cc;">Name</span><span style="color: #006600; font-weight:bold;">&#41;</span> <span style="color: #000000; font-weight: bold;">%&gt;</span><span style="color: #000000; font-weight: bold;">&lt;%</span><span style="color: #006600; font-weight: bold;">=</span> Html.<span style="color: #9900cc;">ValidationMessageFor</span><span style="color: #006600; font-weight:bold;">&#40;</span>x <span style="color: #006600; font-weight: bold;">=&gt;</span> x.<span style="color: #9900cc;">Name</span><span style="color: #006600; font-weight:bold;">&#41;</span> <span style="color: #000000; font-weight: bold;">%&gt;</span>			
	&lt;br /&gt;
	Email: <span style="color: #000000; font-weight: bold;">&lt;%</span><span style="color: #006600; font-weight: bold;">=</span>Html.<span style="color: #9900cc;">TextBoxFor</span><span style="color: #006600; font-weight:bold;">&#40;</span>x <span style="color: #006600; font-weight: bold;">=&gt;</span> x.<span style="color: #9900cc;">Email</span><span style="color: #006600; font-weight:bold;">&#41;</span> <span style="color: #000000; font-weight: bold;">%&gt;</span><span style="color: #000000; font-weight: bold;">&lt;%</span><span style="color: #006600; font-weight: bold;">=</span> Html.<span style="color: #9900cc;">ValidationMessageFor</span><span style="color: #006600; font-weight:bold;">&#40;</span>x <span style="color: #006600; font-weight: bold;">=&gt;</span> x.<span style="color: #9900cc;">Email</span><span style="color: #006600; font-weight:bold;">&#41;</span> <span style="color: #000000; font-weight: bold;">%&gt;</span>
	&lt;br /&gt;
	Age: <span style="color: #000000; font-weight: bold;">&lt;%</span><span style="color: #006600; font-weight: bold;">=</span> Html.<span style="color: #9900cc;">TextBoxFor</span><span style="color: #006600; font-weight:bold;">&#40;</span>x <span style="color: #006600; font-weight: bold;">=&gt;</span> x.<span style="color: #9900cc;">Age</span><span style="color: #006600; font-weight:bold;">&#41;</span> <span style="color: #000000; font-weight: bold;">%&gt;</span><span style="color: #000000; font-weight: bold;">&lt;%</span><span style="color: #006600; font-weight: bold;">=</span> Html.<span style="color: #9900cc;">ValidationMessageFor</span><span style="color: #006600; font-weight:bold;">&#40;</span>x <span style="color: #006600; font-weight: bold;">=&gt;</span> x.<span style="color: #9900cc;">Age</span><span style="color: #006600; font-weight:bold;">&#41;</span> <span style="color: #000000; font-weight: bold;">%&gt;</span>
&nbsp;
	&lt;br /&gt;&lt;br /&gt;
&nbsp;
	&lt;input type=&quot;submit&quot; value=&quot;submit&quot; /&gt;
<span style="color: #000000; font-weight: bold;">&lt;%</span> <span style="color: #006600; font-weight:bold;">&#125;</span> <span style="color: #000000; font-weight: bold;">%&gt;</span></pre></div></div>

<p>
Now when you post the form MVC&#8217;s DefaultModelBinder will validate the Person object using the FluentValidationModelValidatorProvider.
</p>
<h3>Clientside Validation</h3>
<p>
This release also has preliminary support for clientside validation. This is enabled by calling <strong>&lt;% Html.EnableClientValidation(); %&gt;</strong> in your views. At the moment, only the NotNull, NotEmpty, RegularExpression and Length validators are supported.
</p>
<p>
Note that if you try to use the clientside validation support with the default error messages, you will see error messages like this:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #666666;">'{PropertyName}'</span> must not be empty.</pre></div></div>

<p>
This is because FluentValidation uses templated error messages but the MVC Framework&#8217;s clientside validation runner does not know how to correctly format these. For now, the only workaround is to explicitly specify the error message:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">RuleFor<span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Surname</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">NotNull</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">WithMessage</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;'Surname' must not be empty&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>
For FluentValidation 1.3 I will consider providing a customised version of MVC&#8217;s MicrosoftMvcValidation.js that knows how to properly format FluentValidation error templates.
</p>
<h3>
Metadata Support<br />
</h3>
<p>
Out of the box, MVC2 allows you to use the DataAnnotations attributes to provide <a href="http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-2-modelmetadata.html">metadata for editor/display templates</a>. This release of FluentValidation allows you to use extra extension methods on your validator classes to define metadata using method chaining.
</p>
<p>
Firstly, you will need to replace the DataAnnotationsModelMetadataProvider with the new FluentValidationModelMetadataProvider in your Application_Start:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">ModelMetadataProviders.<span style="color: #0000FF;">Current</span> <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> FluentValidationModelMetadataProvider<span style="color: #000000;">&#40;</span>
	<span style="color: #008000;">new</span> AttributedValidatorFactory<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>
Now you can start using the metadata extension in your validator classes (you will need to import the FluentValidation.Mvc.MetadataExtensions namespace):
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> CustomerValidator<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
   RuleFor<span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Surname</span><span style="color: #000000;">&#41;</span>
      .<span style="color: #0000FF;">NotNull</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008080; font-style: italic;">//regular validator</span>
      .<span style="color: #0000FF;">UIHint</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Surname&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">//MVC Metadata</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
The FluentValidationModelMetadataProvider currently supports the following metadata-related extension methods which correspond to the DataAnnotations attributes with the same name:</p>
<ul>
<li>HiddenInput</li>
<li>UIHint</li>
<li>Scaffold</li>
<li>DataType</li>
<li>DisplayName</li>
<li>DisplayFormat</li>
<li>ReadOnly</li>
</ul>
<p>
<strong>Edit: 8th Feb</strong>Note that there is a bug in the current beta build where MetaData won&#8217;t work in some circumstances. This is already fixed for the next beta, so you may want to use the latest binaries from <a href="http://build.jeremyskinner.co.uk/repository/download/bt2/.lastSuccessful/FluentValidation.zip?guest=1">the build server</a>.
</p>
<p>
As usual, binaries are <a href="http://fluentvalidation.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=40035">on CodePlex</a> and the source is <a href="http://github.com/JeremySkinner/FluentValidation">on GitHub</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeremyskinner.co.uk/2010/02/06/fluentvalidation-1-2-beta-2-and-mvc2-rc2/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
		<item>
		<title>Linq to Sql and ASP.NET MVC &#8211; DataLoadOptions per Request</title>
		<link>http://www.jeremyskinner.co.uk/2010/02/02/linq-to-sql-and-asp-net-mvc-dataloadoptions-per-request/</link>
		<comments>http://www.jeremyskinner.co.uk/2010/02/02/linq-to-sql-and-asp-net-mvc-dataloadoptions-per-request/#comments</comments>
		<pubDate>Tue, 02 Feb 2010 13:47:30 +0000</pubDate>
		<dc:creator>Jeremy Skinner</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://www.jeremyskinner.co.uk/?p=329</guid>
		<description><![CDATA[This is the third in a series of posts on using ASP.NET MVC with Linq to Sql: Part 1 &#8211; DataContext Per Request Part 2 &#8211; AutoCommit and the RoutePreParser Part 3 &#8211; DataLoadOptions per Request Code for this series is available here. One common problem when using an ORM is the issue of &#8220;select [...]]]></description>
			<content:encoded><![CDATA[<p>
This is the third in a series of posts on using ASP.NET MVC with Linq to Sql:
</p>
<ul>
<li>Part 1 &#8211; <a href="http://www.jeremyskinner.co.uk/2010/01/31/linq-to-sql-and-asp-net-mvc-datacontext-per-request/">DataContext Per Request</a></li>
<li>Part 2 &#8211; <a href="http://www.jeremyskinner.co.uk/2010/02/01/linq-to-sql-and-asp-net-mvc-autocommit-and-the-routepreparser/">AutoCommit and the RoutePreParser</a></li>
<li>Part 3 &#8211; <a href="http://www.jeremyskinner.co.uk/2010/02/02/linq-to-sql-and-asp-net-mvc-dataloadoptions-per-request/">DataLoadOptions per Request</a></li>
</ul>
<p>
Code for this series is <a href="http://cloud.github.com/downloads/JeremySkinner/Experiments/LinqToSqlWithMvc.zip">available here</a>.
</p>
<p>
One common problem when using an ORM is the issue of &#8220;select n+1&#8243;. For example, take the following Linq to Sql query:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var context <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> BlogDataContext<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
var posts <span style="color: #008000;">=</span> context.<span style="color: #0000FF;">Posts</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF;">foreach</span><span style="color: #000000;">&#40;</span>var post <span style="color: #0600FF;">in</span> posts<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
   <span style="color: #0600FF;">foreach</span><span style="color: #000000;">&#40;</span>var comment <span style="color: #0600FF;">in</span> post.<span style="color: #0000FF;">Comments</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
     var commenter <span style="color: #008000;">=</span> comment.<span style="color: #0000FF;">Commenter</span>.<span style="color: #0000FF;">Name</span><span style="color: #008000;">;</span>
     Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;User {0} commented on post {1}&quot;</span>, commenter, post.<span style="color: #0000FF;">Title</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
   <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
This might look fine on the surface, but by default Linq to Sql will lazily-load all associations. This means that for each post loaded from the database Linq to Sql will issue a query to load the comments, and for each comment Linq to Sql will issue another query to load the commenter. So if you have 10 posts, and each post has 5 comments then you&#8217;ll end up making 61 queries to the database (1 for the posts, 1 for each post to get the comments, and 1 for each comment to get the user)
</p>
<p>
This can be mitigated by using DataLoadOptions to eagerly load all of the data in a single query:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var context <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> BlogDataContext<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
var options <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> DataLoadOptions<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
options.<span style="color: #0000FF;">LoadWith</span><span style="color: #008000;">&lt;</span>Post<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>p <span style="color: #008000;">=&gt;</span> p.<span style="color: #0000FF;">Comments</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
options.<span style="color: #0000FF;">LoadWith</span><span style="color: #008000;">&lt;</span>Comment<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>c <span style="color: #008000;">=&gt;</span> c.<span style="color: #0000FF;">Commenter</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
context.<span style="color: #0000FF;">LoadOptions</span> <span style="color: #008000;">=</span> options<span style="color: #008000;">;</span>
&nbsp;
var posts <span style="color: #008000;">=</span> context.<span style="color: #0000FF;">Posts</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">foreach</span><span style="color: #000000;">&#40;</span>var post <span style="color: #0600FF;">in</span> posts<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
 <span style="color: #008080; font-style: italic;">//...</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<h3>The Problem</h3>
<p>
However, once a query has been executed, the LoadOptions property of a DataContext is frozen &#8211; you cannot then specify any additional eager loading paths.*
</p>
<p>
If you&#8217;re using a DataContext per request <a href="http://www.jeremyskinner.co.uk/2010/01/31/linq-to-sql-and-asp-net-mvc-datacontext-per-request/">as per my previous post</a> then this can be a problem. For example, imagine you have the following controller action:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> PostsController <span style="color: #008000;">:</span> Controller <span style="color: #000000;">&#123;</span>
  <span style="color: #0600FF;">private</span> BlogDataContext context<span style="color: #008000;">;</span>
&nbsp;
  <span style="color: #0600FF;">public</span> PostsController<span style="color: #000000;">&#40;</span>BlogDataContext context<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
     <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">context</span> <span style="color: #008000;">=</span> context<span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">//injected via our IoC container</span>
  <span style="color: #000000;">&#125;</span>
&nbsp;
  <span style="color: #0600FF;">public</span> ActionResult Show<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> id<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
    var options <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> DataLoadOptions<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    options.<span style="color: #0000FF;">LoadWith</span><span style="color: #008000;">&lt;</span>Post<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>p <span style="color: #008000;">=&gt;</span> p.<span style="color: #0000FF;">Comments</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    options.<span style="color: #0000FF;">LoadWith</span><span style="color: #008000;">&lt;</span>Comment<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>c <span style="color: #008000;">=&gt;</span> c.<span style="color: #0000FF;">Commenter</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    context.<span style="color: #0000FF;">LoadOptions</span> <span style="color: #008000;">=</span> options<span style="color: #008000;">;</span>
&nbsp;
    var post <span style="color: #008000;">=</span> context.<span style="color: #0000FF;">Posts</span>.<span style="color: #0000FF;">Single</span><span style="color: #000000;">&#40;</span>p <span style="color: #008000;">=&gt;</span> p.<span style="color: #0000FF;">Id</span> <span style="color: #008000;">==</span> id<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF;">return</span> View<span style="color: #000000;">&#40;</span>post<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
&#8230;then this will work as expected. But now imagine your action is decorated by an ActionFilter:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>LoadCurrentUser<span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> ActionResult Show<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> id<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span> 
  <span style="color: #008080; font-style: italic;">//...</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
&#8230;and let&#8217;s assume that our LoadCurrentUser filter attempts to load the details of the current user from the database and store them in ViewData:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> LoadCurrentUserAttribute <span style="color: #008000;">:</span> ActionFilterAttribute <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> <span style="color: #0600FF;">void</span> OnActionExecuting<span style="color: #000000;">&#40;</span>ActionExecutingContext filterContext<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		var context <span style="color: #008000;">=</span> ObjectFactory.<span style="color: #0000FF;">GetInstance</span><span style="color: #008000;">&lt;</span>BlogDataContext<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
		var identity <span style="color: #008000;">=</span> filterContext.<span style="color: #0000FF;">HttpContext</span>.<span style="color: #0000FF;">User</span>.<span style="color: #0000FF;">Identity</span><span style="color: #008000;">;</span>
&nbsp;
		<span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>identity.<span style="color: #0000FF;">IsAuthenticated</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
			var currentUser <span style="color: #008000;">=</span> context.<span style="color: #0000FF;">Users</span>.<span style="color: #0000FF;">Single</span><span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">UserName</span> <span style="color: #008000;">==</span> identity.<span style="color: #0000FF;">Name</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
			filterContext.<span style="color: #0000FF;">Controller</span>.<span style="color: #0000FF;">ViewData</span><span style="color: #000000;">&#91;</span><span style="color: #666666;">&quot;CurrentUser&quot;</span><span style="color: #000000;">&#93;</span> <span style="color: #008000;">=</span> currentUser<span style="color: #008000;">;</span>
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
Now when the controller is executed we will get the following error:
</p>
<p>
<em><br />
 Setting load options is not allowed after results have been returned from a query.<br />
</em>
</p>
<p>
This happens because we&#8217;re trying to set the LoadOptions for the Post after the LoadCurrentUser filter already executed a query.
</p>
<h3>The Solution</h3>
<p>
The approach I use to work around this problem is to use a custom AuthorizationFilter in conjunction with an eager loading specification.
</p>
<p>
First, we define an interface for eager loading specifications:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">interface</span> IEagerLoadingSpecification <span style="color: #000000;">&#123;</span>
  <span style="color: #0600FF;">void</span> Build<span style="color: #000000;">&#40;</span>DataLoadOptions options<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
Next, we can write some classes that implement IEagerLoadingSpecification that define particular specifications for eager loading. Using the example above, we have PostWithComments and CommentWithCommenter:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> PostWithComments <span style="color: #008000;">:</span> IEagerLoadingSpecification <span style="color: #000000;">&#123;</span>
  <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Build<span style="color: #000000;">&#40;</span>DataLoadOptions options<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
    options.<span style="color: #0000FF;">LoadWith</span><span style="color: #008000;">&lt;</span>Post<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>p <span style="color: #008000;">=&gt;</span> p.<span style="color: #0000FF;">Comments</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> CommentWithCommenter <span style="color: #008000;">:</span> IEagerLoadingSpecification  <span style="color: #000000;">&#123;</span>
  <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Build<span style="color: #000000;">&#40;</span>DataLoadOptions options<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
     options.<span style="color: #0000FF;">LoadWith</span><span style="color: #008000;">&lt;</span>Comment<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>c <span style="color: #008000;">=&gt;</span> c.<span style="color: #0000FF;">Commenter</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
Next, we write an EagerlyLoadAttribute which implements IAuthorizationFilter and takes an array of Types in its constructor:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> EagerlyLoadAttribute <span style="color: #008000;">:</span> FilterAttribute, IAuthorizationFilter <span style="color: #000000;">&#123;</span>
  <span style="color: #0600FF;">private</span> Type<span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> types<span style="color: #008000;">;</span>
&nbsp;
  <span style="color: #0600FF;">public</span> EagerlyLoadAttribute<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">params</span> Type<span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> types<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">types</span> <span style="color: #008000;">=</span> types<span style="color: #008000;">;</span>
  <span style="color: #000000;">&#125;</span>
&nbsp;
  <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> OnAuthorization<span style="color: #000000;">&#40;</span>AuthorizationContext filterContext<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
    var loadOptions <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> DataLoadOptions<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    var context <span style="color: #008000;">=</span> ObjectFactory.<span style="color: #0000FF;">GetInstance</span><span style="color: #008000;">&lt;</span>BlogDataContext<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">foreach</span><span style="color: #000000;">&#40;</span>var type <span style="color: #0600FF;">in</span> types<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
       <span style="color: #0600FF;">if</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">!</span> <span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span>IEagerLoadingSpecification<span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">IsAssignableFrom</span><span style="color: #000000;">&#40;</span>type<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
          <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> InvalidOperationException<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span>.<span style="color: #0000FF;">Format</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Type {0} does not implement IEagerLoadingSpecification&quot;</span>, type<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
       <span style="color: #000000;">&#125;</span>
&nbsp;
      var spec <span style="color: #008000;">=</span> <span style="color: #000000;">&#40;</span>IEagerLoadingSpecification<span style="color: #000000;">&#41;</span>Activator.<span style="color: #0000FF;">CreateInstance</span><span style="color: #000000;">&#40;</span>type<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
      spec.<span style="color: #0000FF;">Build</span><span style="color: #000000;">&#40;</span>loadOptions<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
   context.<span style="color: #0000FF;">LoadOptions</span> <span style="color: #008000;">=</span> loadOptions<span style="color: #008000;">;</span>
  <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
So what does this filter do? Firstly, because it implements IAuthorizationFilter this means it will be invoked before any action filters that decorate your controller action. When OnAuthorization is invoked, it loops over each of the Types that we&#8217;ve passed to its constructor, instantiates them and casts them to IEagerLoadingSpecification. Next, a single DataLoadOptions instance is passed to each of the specifications in turn so they can build up the required eager loading paths.
</p>
<p>
The end result is that you can now define your actions like this:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">  <span style="color: #000000;">&#91;</span>EagerlyLoad<span style="color: #000000;">&#40;</span><span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span>PostWithComments<span style="color: #000000;">&#41;</span>, <span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span>CommentWithCommenter<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
  <span style="color: #000000;">&#91;</span>LoadCurrentUser<span style="color: #000000;">&#93;</span>
  <span style="color: #0600FF;">public</span> ActionResult Show<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> id<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
    var post <span style="color: #008000;">=</span> context.<span style="color: #0000FF;">Posts</span>.<span style="color: #0000FF;">Single</span><span style="color: #000000;">&#40;</span>p <span style="color: #008000;">=&gt;</span> p.<span style="color: #0000FF;">Id</span> <span style="color: #008000;">==</span> id<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF;">return</span> View<span style="color: #000000;">&#40;</span>post<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #000000;">&#125;</span></pre></div></div>

<p>
Because the EagerlyLoadAttribute is an IAuthorizationFilter, it will be invoked before anything else meaning that by the time both our LoadCurrentUser filter and the Show action are invoked the DataLoadOptions have already been set on our DataContext.
</p>
<p>
* Note that other ORMs like NHibernate, LLBLGen and the Entity Framework don&#8217;t have this problem because they allow eager loading paths to be specified at the query level.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeremyskinner.co.uk/2010/02/02/linq-to-sql-and-asp-net-mvc-dataloadoptions-per-request/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Linq to Sql and ASP.NET MVC &#8211; AutoCommit and the RoutePreParser</title>
		<link>http://www.jeremyskinner.co.uk/2010/02/01/linq-to-sql-and-asp-net-mvc-autocommit-and-the-routepreparser/</link>
		<comments>http://www.jeremyskinner.co.uk/2010/02/01/linq-to-sql-and-asp-net-mvc-autocommit-and-the-routepreparser/#comments</comments>
		<pubDate>Mon, 01 Feb 2010 12:28:53 +0000</pubDate>
		<dc:creator>Jeremy Skinner</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://www.jeremyskinner.co.uk/?p=298</guid>
		<description><![CDATA[This is the second in a series of posts on using ASP.NET MVC with Linq to Sql: Part 1 &#8211; DataContext Per Request Part 2 &#8211; AutoCommit and the RoutePreParser Part 3 &#8211; DataLoadOptions per Request Code for this series is available here. In my previoust post, I demonstrated how you could scope a Linq [...]]]></description>
			<content:encoded><![CDATA[<p>
This is the second in a series of posts on using ASP.NET MVC with Linq to Sql:
</p>
<ul>
<li>Part 1 &#8211; <a href="http://www.jeremyskinner.co.uk/2010/01/31/linq-to-sql-and-asp-net-mvc-datacontext-per-request/">DataContext Per Request</a></li>
<li>Part 2 &#8211; <a href="http://www.jeremyskinner.co.uk/2010/02/01/linq-to-sql-and-asp-net-mvc-autocommit-and-the-routepreparser/">AutoCommit and the RoutePreParser</a></li>
<li>Part 3 &#8211; <a href="http://www.jeremyskinner.co.uk/2010/02/02/linq-to-sql-and-asp-net-mvc-dataloadoptions-per-request/">DataLoadOptions per Request</a></li>
</ul>
<p>
Code for this series is <a href="http://cloud.github.com/downloads/JeremySkinner/Experiments/LinqToSqlWithMvc.zip">available here</a>.
</p>
<p>
In my previoust post, I demonstrated how you could scope a Linq to Sql DataContext to a single HTTP Request by using StructureMap to manage the lifetime of the DataContext instance. This often works well, but has a couple of gotchas. Let&#8217;s take a look at an example:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> PostController <span style="color: #008000;">:</span> Controller <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">private</span> <span style="color: #0600FF;">readonly</span> BlogDataContext context<span style="color: #008000;">;</span>
&nbsp;
	<span style="color: #0600FF;">public</span> PostController<span style="color: #000000;">&#40;</span>BlogDataContext context<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">context</span> <span style="color: #008000;">=</span> context<span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF;">public</span> ActionResult Create<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">return</span> View<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #000000;">&#91;</span>AcceptVerbs<span style="color: #000000;">&#40;</span>HttpVerbs.<span style="color: #0000FF;">Post</span><span style="color: #000000;">&#41;</span>, AutoCommit<span style="color: #000000;">&#93;</span>
	<span style="color: #0600FF;">public</span> ActionResult Create<span style="color: #000000;">&#40;</span>Post post<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		context.<span style="color: #0000FF;">Posts</span>.<span style="color: #0000FF;">InsertOnSubmit</span><span style="color: #000000;">&#40;</span>post<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
		<span style="color: #0600FF;">return</span> RedirectToAction<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Show&quot;</span>, <span style="color: #008000;">new</span><span style="color: #000000;">&#123;</span> id <span style="color: #008000;">=</span> post.<span style="color: #0000FF;">Id</span> <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF;">public</span> ActionResult Show<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> id<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		var post <span style="color: #008000;">=</span> context.<span style="color: #0000FF;">Posts</span>.<span style="color: #0000FF;">SingleOrDefault</span><span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Id</span> <span style="color: #008000;">==</span> id<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
		<span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>post <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
			<span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> HttpException<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">404</span>, <span style="color: #666666;">&quot;The post could not be found.&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0600FF;">return</span> View<span style="color: #000000;">&#40;</span>post<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
In this example, we have a Post controller for our fictional Blog database. The Create action renders a view where the user can create a new Post and then sends an HTTP POST to the other overload to the Create action (decorated with AcceptVerbs(HttpVerbs.Post)).
</p>
<p>
This action is decorated with the AutoCommit attribute from my <a href="http://www.jeremyskinner.co.uk/2010/01/31/linq-to-sql-and-asp-net-mvc-datacontext-per-request/">previous post</a> so that SubmitChanges will automatically be called on our DataContext. We then redirect to the &#8220;Show&#8221; action passing the Id of the newly created post in the route data.
</p>
<p>
The Show action loads the Post from the database with the corresponding Id and displays it to the user. If a post with the specified Id could not be found, it will throw a 404 exception.
</p>
<p>
There is a bug here that may not be immediately obvious. Assume that the Post&#8217;s Id property is generated by an auto-incrementing Identity field in the database. If you were to run this application and create a new Post, the Show action <strong>will always throw 404 even though the Post has been successfully created.</strong></p>
<p>This happens because of when SubmitChanges is called. Our AutoCommit filter is invoked <strong>after the action has finished executing</strong> this means that at the time we call RedirectToAction(&#8220;Show&#8221;, new{ id = post.Id }) the new post <strong>has not yet been saved, so its Id will be 0</strong>.</p>
<p>Linq to Sql will not update the Id property until after SubmitChanges is called, which is too late in the process. The user will end up being redirected to Post/Show/0 instead of using the Id of the newly created post.
</p>
<p>
The simple workaround is to call SubmitChanges directly inside the action:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>AcceptVerbs<span style="color: #000000;">&#40;</span>HttpVerbs.<span style="color: #0000FF;">Post</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> ActionResult Create<span style="color: #000000;">&#40;</span>Post post<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
	context.<span style="color: #0000FF;">Posts</span>.<span style="color: #0000FF;">InsertOnSubmit</span><span style="color: #000000;">&#40;</span>post<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	<span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>ModelState.<span style="color: #0000FF;">IsValid</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">using</span> <span style="color: #000000;">&#40;</span>var transaction <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> TransactionScope<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
			context.<span style="color: #0000FF;">SubmitChanges</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
			transaction.<span style="color: #0000FF;">Complete</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF;">return</span> RedirectToAction<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Show&quot;</span>, <span style="color: #008000;">new</span> <span style="color: #000000;">&#123;</span> id <span style="color: #008000;">=</span> post.<span style="color: #0000FF;">Id</span> <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
&#8230;but this then makes our AutoCommit attribute useless and also makes the controller action significantly more complex.
</p>
<p>
However, there is another approach we could use which still allows us to use the AutoCommit attribute. To understand this, we first need to look at the order in which things are happening when our action is invoked:
</p>
<ol>
<li>The IoC container creates our DataContext</li>
<li>The controller is instantiated and the DataContext is passed to its constructor</li>
<li>The Create action is invoked with a Post instance created by MVC&#8217;s DefaultModelBinder</li>
<li>The post is attached to the DataContext by calling InsertOnSubmit</li>
<li>A RedirectToRouteResult is created by calling &#8220;RedirectToAction&#8221; with a dictionary of route values</li>
<li>The AutoCommit attribute calls SubmitChanges to our DataContext</li>
<li>The Post is written to the database</li>
<li>ExecuteResult on RedirectToRouteResult is invoked</li>
<li>The Redirect URL is generated by the RouteCollection</li>
<li>The user&#8217;s browser is redirected to this URL</li>
</ol>
<p>
Instead of passing the Post Id (which will be 0) to RedirectToAction, <strong>we could pass the entire post instance.</strong> After the post has been saved we can then *replace* the post instance in the RouteValueDictionary with the post&#8217;s Id before the URL is generated. This can be done by intercepting the RouteValueDictionary just before the URL is generated.
</p>
<h3>Introducing the RoutePreParser</h3>
<p>
The first thing we need is a way to identify how an object (in this case, our Post) should be converted to a route value. To do this, we can create an interface, IUrlRoutable:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">interface</span> IUrlRoutable <span style="color: #000000;">&#123;</span>
	<span style="color: #FF0000;">object</span> GetRouteParameter<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
&#8230;and we can implement this interface in our Post class:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #0600FF;">partial</span> <span style="color: #FF0000;">class</span> Post <span style="color: #008000;">:</span> IUrlRoutable <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">object</span> GetRouteParameter<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">return</span> Id<span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
Next we can create a &#8220;fake&#8221; route. This route never generates a URL or handles a request &#8211; it is merely used to intercept the RouteValueDictionary before a URL is generated:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> RoutePreParser <span style="color: #008000;">:</span> RouteBase <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> RouteData GetRouteData<span style="color: #000000;">&#40;</span>HttpContextBase httpContext<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">return</span> null<span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> VirtualPathData GetVirtualPath<span style="color: #000000;">&#40;</span>RequestContext requestContext, RouteValueDictionary values<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		var query <span style="color: #008000;">=</span> from pair <span style="color: #0600FF;">in</span> values
				where pair.<span style="color: #0000FF;">Value</span> <span style="color: #008000;">!=</span> <span style="color: #0600FF;">null</span>
				let routable <span style="color: #008000;">=</span> pair.<span style="color: #0000FF;">Value</span> <span style="color: #0600FF;">as</span> IUrlRoutable
				where routable <span style="color: #008000;">!=</span> <span style="color: #0600FF;">null</span>
				select <span style="color: #008000;">new</span> <span style="color: #000000;">&#123;</span> pair.<span style="color: #0000FF;">Key</span>, Value <span style="color: #008000;">=</span> routable.<span style="color: #0000FF;">GetRouteParameter</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#125;</span><span style="color: #008000;">;</span>
&nbsp;
		<span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>var pair <span style="color: #0600FF;">in</span> query.<span style="color: #0000FF;">ToList</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
			values<span style="color: #000000;">&#91;</span>pair.<span style="color: #0000FF;">Key</span><span style="color: #000000;">&#93;</span> <span style="color: #008000;">=</span> pair.<span style="color: #0000FF;">Value</span><span style="color: #008000;">;</span>
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0600FF;">return</span> null<span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
Here we loop through each key-value pair in the RouteValueDictionary. If the value implements IUrlRoutable then we call GetRouteParameter on that object and <strong>replace the original value in the RouteValueDictionary with the result of this method.</strong>
</p>
<p>
Next, we have to add the fake route to the RouteCollection in Application_Start. Note that this <strong>must be the first route added so that it gets a chance to intercept the RouteValueDictionary.</strong>
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> RegisterRoutes<span style="color: #000000;">&#40;</span>RouteCollection routes<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
	<span style="color: #008080; font-style: italic;">//Add our fake route first</span>
	routes.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> RoutePreParser<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	routes.<span style="color: #0000FF;">IgnoreRoute</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;{resource}.axd/{*pathInfo}&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	routes.<span style="color: #0000FF;">MapRoute</span><span style="color: #000000;">&#40;</span>
		<span style="color: #666666;">&quot;Default&quot;</span>, <span style="color: #008080; font-style: italic;">// Route name</span>
		<span style="color: #666666;">&quot;{controller}/{action}/{id}&quot;</span>, <span style="color: #008080; font-style: italic;">// URL with parameters</span>
		<span style="color: #008000;">new</span> <span style="color: #000000;">&#123;</span> controller <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Home&quot;</span>, action <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Index&quot;</span>, id <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;&quot;</span> <span style="color: #000000;">&#125;</span> <span style="color: #008080; font-style: italic;">// Parameter defaults</span>
	<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
Now, in our controller action we change the Create action to store the Post instance in the route values:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>AcceptVerbs<span style="color: #000000;">&#40;</span>HttpVerbs.<span style="color: #0000FF;">Post</span><span style="color: #000000;">&#41;</span>, AutoCommit<span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> ActionResult Create<span style="color: #000000;">&#40;</span>Post post<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
	context.<span style="color: #0000FF;">Posts</span>.<span style="color: #0000FF;">InsertOnSubmit</span><span style="color: #000000;">&#40;</span>post<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #0600FF;">return</span> RedirectToAction<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Show&quot;</span>, <span style="color: #008000;">new</span><span style="color: #000000;">&#123;</span> id <span style="color: #008000;">=</span> post <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
&#8230;and everything now works as expected.
</p>
<p>
To recap, this is the new chain of events:
</p>
<ol>
<li>The IoC container creates our DataContext</li>
<li>The controller is instantiated and the DataContext is passed to its constructor</li>
<li>The Create action is invoked with a Post instance created by MVC&#8217;s DefaultModelBinder</li>
<li>The post is attached to the DataContext by calling InsertOnSubmit</li>
<li>A RedirectToRouteResult is created by calling &#8220;RedirectToAction&#8221; with a dictionary of route values. (The &#8220;Id&#8221; parameter is our new Post instance.)
</li>
<li>The AutoCommit attribute calls SubmitChanges to our DataContext</li>
<li>The Post is written to the database</li>
<li>The Post instance stored in the RouteValueDictionary automatically has its Id property updated</li>
<li>ExecuteResult on RedirectToRouteResult is invoked</li>
<li>Our RoutePreParser inspects the RouteValueDictionary.</li>
<li>GetRouteParameter on Post is invoked, returning the now-populated Post Id</li>
<li>The RoutePreParser removes the Post instance from the RouteValueDictionary</li>
<li>The RoutePreParser inserts the Post Id as the &#8220;id&#8221; in the RouteValueDictionary</li>
<li>The (now correct) redirect URL is generated by the RouteCollection</li>
<li>The user&#8217;s browser is redirected to this URL</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://www.jeremyskinner.co.uk/2010/02/01/linq-to-sql-and-asp-net-mvc-autocommit-and-the-routepreparser/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Linq to Sql and ASP.NET MVC &#8211; DataContext Per Request</title>
		<link>http://www.jeremyskinner.co.uk/2010/01/31/linq-to-sql-and-asp-net-mvc-datacontext-per-request/</link>
		<comments>http://www.jeremyskinner.co.uk/2010/01/31/linq-to-sql-and-asp-net-mvc-datacontext-per-request/#comments</comments>
		<pubDate>Sun, 31 Jan 2010 11:45:23 +0000</pubDate>
		<dc:creator>Jeremy Skinner</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://www.jeremyskinner.co.uk/?p=292</guid>
		<description><![CDATA[This is the first in a series of posts about using Linq to Sql with ASP.NET MVC. Part 1 &#8211; DataContext Per Request Part 2 &#8211; AutoCommit and the RoutePreParser Part 3 &#8211; DataLoadOptions per Request Code for this series is available here. When using an ORM tool within a web application, it&#8217;s often common [...]]]></description>
			<content:encoded><![CDATA[<p>
This is the first in a series of posts about using Linq to Sql with ASP.NET MVC.
</p>
<ul>
<li>Part 1 &#8211; <a href="http://www.jeremyskinner.co.uk/2010/01/31/linq-to-sql-and-asp-net-mvc-datacontext-per-request/">DataContext Per Request</a></li>
<li>Part 2 &#8211; <a href="http://www.jeremyskinner.co.uk/2010/02/01/linq-to-sql-and-asp-net-mvc-autocommit-and-the-routepreparser/">AutoCommit and the RoutePreParser</a></li>
<li>Part 3 &#8211; <a href="http://www.jeremyskinner.co.uk/2010/02/02/linq-to-sql-and-asp-net-mvc-dataloadoptions-per-request/">DataLoadOptions per Request</a></li>
</ul>
<p>
Code for this series is <a href="http://cloud.github.com/downloads/JeremySkinner/Experiments/LinqToSqlWithMvc.zip">available here</a>.
</p>
<p>
When using an ORM tool within a web application, it&#8217;s often common to scope a unit of work to the lifetime of an HTTP Request. If you&#8217;re using Linq to Sql and ASP.NET MVC, you can achieve this by using an Inversion of Control container in conjunction with an ActionFilter.
</p>
<p>
For this example, I&#8217;m going to be using the <a href="http://structuremap.sourceforge.net/Default.htm">StructureMap</a> IoC container alongside a fictional &#8220;Blog&#8221; database.
</p>
<p>
Firstly, you&#8217;ll need to configure StructureMap by calling ObjectFactory.Configure inside your Global.asax passing in a custom Registry instance:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">void</span> Application_Start<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
	RegisterRoutes<span style="color: #000000;">&#40;</span>RouteTable.<span style="color: #0000FF;">Routes</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	ObjectFactory.<span style="color: #0000FF;">Configure</span><span style="color: #000000;">&#40;</span>cfg <span style="color: #008000;">=&gt;</span> <span style="color: #000000;">&#123;</span>
		cfg.<span style="color: #0000FF;">AddRegistry</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> MyRegistry<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>The code for MyRegistry looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> MyRegistry <span style="color: #008000;">:</span> Registry <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> MyRegistry<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">For</span><span style="color: #008000;">&lt;</span>BlogDataContext<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
			.<span style="color: #0000FF;">HttpContextScoped</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
			.<span style="color: #0000FF;">Use</span><span style="color: #000000;">&#40;</span>c <span style="color: #008000;">=&gt;</span> <span style="color: #008000;">new</span> BlogDataContext<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
		Scan<span style="color: #000000;">&#40;</span>scan <span style="color: #008000;">=&gt;</span> <span style="color: #000000;">&#123;</span>
			scan.<span style="color: #0000FF;">AddAllTypesOf</span><span style="color: #008000;">&lt;</span>Controller<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
		<span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
Here I&#8217;m telling StructureMap to create one instance of my BlogDataContext per HTTP Request as well as registering each Controller instance with the container.
</p>
<p>
Next, we need to tell MVC to use StructureMap to instantiate our controllers. This can be done by creating a custom ControllerFactory:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> StructureMapControllerFactory <span style="color: #008000;">:</span> DefaultControllerFactory <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">override</span> IController GetControllerInstance<span style="color: #000000;">&#40;</span>RequestContext requestContext, Type controllerType<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">return</span> <span style="color: #000000;">&#40;</span>IController<span style="color: #000000;">&#41;</span> ObjectFactory.<span style="color: #0000FF;">GetInstance</span><span style="color: #000000;">&#40;</span>controllerType<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
We can then replace the DefaultControllerFactory with the StructureMapControllerFactory in our Application_Start:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">void</span> Application_Start<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
	RegisterRoutes<span style="color: #000000;">&#40;</span>RouteTable.<span style="color: #0000FF;">Routes</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	ObjectFactory.<span style="color: #0000FF;">Configure</span><span style="color: #000000;">&#40;</span>cfg <span style="color: #008000;">=&gt;</span> <span style="color: #000000;">&#123;</span>
		cfg.<span style="color: #0000FF;">AddRegistry</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> MyRegistry<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	ControllerBuilder.<span style="color: #0000FF;">Current</span>.<span style="color: #0000FF;">SetControllerFactory</span><span style="color: #000000;">&#40;</span>
		<span style="color: #008000;">new</span> StructureMapControllerFactory<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
Now, if we create a PostController (for creating and editing Posts in our fictional blog), we can now take a BlogDataContext in the constructor (for better testability, you&#8217;d probably want to hide the DataContext behind an interface):
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> PostController <span style="color: #008000;">:</span> Controller <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">private</span> <span style="color: #0600FF;">readonly</span> BlogDataContext context<span style="color: #008000;">;</span>
&nbsp;
	<span style="color: #0600FF;">public</span> PostController<span style="color: #000000;">&#40;</span>BlogDataContext context<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">context</span> <span style="color: #008000;">=</span> context<span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF;">public</span> ActionResult Edit<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> id<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		var post <span style="color: #008000;">=</span> context.<span style="color: #0000FF;">Posts</span>.<span style="color: #0000FF;">Single</span><span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Id</span> <span style="color: #008000;">==</span> id<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
		<span style="color: #0600FF;">return</span> View<span style="color: #000000;">&#40;</span>post<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
Now, visiting http://mysite/Post/Edit/1 would return a view to display a post with the Id of 1 (assuming the appropriate Post exists in the database).
</p>
<h3>Automatically Submitting Changes</h3>
<p>
We can take this a stage further by adding an ActionFilter to our application that will automatically call SubmitChanges on our DataContext at the end of the HTTP Request:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> AutoCommitAttribute <span style="color: #008000;">:</span> ActionFilterAttribute <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> <span style="color: #0600FF;">void</span> OnActionExecuted<span style="color: #000000;">&#40;</span>ActionExecutedContext filterContext<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>filterContext.<span style="color: #0000FF;">Controller</span>.<span style="color: #0000FF;">ViewData</span>.<span style="color: #0000FF;">ModelState</span>.<span style="color: #0000FF;">IsValid</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
			var currentDataContext <span style="color: #008000;">=</span> ObjectFactory.<span style="color: #0000FF;">GetInstance</span><span style="color: #008000;">&lt;</span>BlogDataContext<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
			<span style="color: #0600FF;">using</span> <span style="color: #000000;">&#40;</span>var transaction <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> TransactionScope<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
				currentDataContext.<span style="color: #0000FF;">SubmitChanges</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
				transaction.<span style="color: #0000FF;">Complete</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
			<span style="color: #000000;">&#125;</span>
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
Here we call into StructureMap to retrieve our current DataContext and commit any changes back to the database inside a transaction. Note that this will only happen if the ModelState is valid (ie there are no validation errors). </p>
<p>Another thing to keep in mind that using an IoC container as a Service Locator (as we&#8217;re doing in this filter) is generally considered bad practice. There are ways <a href="http://www.jeremyskinner.co.uk/2008/11/08/dependency-injection-with-aspnet-mvc-action-filters/">around</a> <a href="http://www.iridescence.no/post/Constructor-Injection-for-ASPNET-MVC-Action-Filters.aspx">this</a> but these are outside the scope of this post.
</p>
<p>
Now, whenever we make a change to one of our entities the change will automatically be committed to the database provided the action is decorated with the AutoCommit attribute:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>AcceptVerbs<span style="color: #000000;">&#40;</span>HttpVerbs.<span style="color: #0000FF;">Post</span><span style="color: #000000;">&#41;</span>, AutoCommit<span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> ActionResult Create<span style="color: #000000;">&#40;</span>Post post<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
	context.<span style="color: #0000FF;">Posts</span>.<span style="color: #0000FF;">InsertOnSubmit</span><span style="color: #000000;">&#40;</span>post<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #0600FF;">return</span> RedirectToAction<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Index&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://www.jeremyskinner.co.uk/2010/01/31/linq-to-sql-and-asp-net-mvc-datacontext-per-request/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Limitations of MVC2&#8242;s ModelValidatorProviders</title>
		<link>http://www.jeremyskinner.co.uk/2010/01/13/limitations-of-mvc2s-modelvalidatorproviders/</link>
		<comments>http://www.jeremyskinner.co.uk/2010/01/13/limitations-of-mvc2s-modelvalidatorproviders/#comments</comments>
		<pubDate>Wed, 13 Jan 2010 11:08:40 +0000</pubDate>
		<dc:creator>Jeremy Skinner</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[FluentValidation]]></category>
		<category><![CDATA[aspnetmvc]]></category>

		<guid isPermaLink="false">http://www.jeremyskinner.co.uk/?p=274</guid>
		<description><![CDATA[Update 6 Feb 2010: Most of the issues that I&#8217;ve mentioned here have been addressed in MVC2 RC2. See this post for details. One of the new features in ASP.NET MVC 2 is the ability the ability to define multiple validation providers. These are used by the DefaultModelBinder to automatically validate your model objects when [...]]]></description>
			<content:encoded><![CDATA[<p>
<strong>Update 6 Feb 2010:</strong> Most of the issues that I&#8217;ve mentioned here have been addressed in MVC2 RC2. See <a href="http://www.jeremyskinner.co.uk/2010/02/06/fluentvalidation-1-2-beta-2-and-mvc2-rc2/">this post</a> for details.
</p>
<p>
One of the new features in ASP.NET MVC 2 is the ability the ability to define multiple validation providers. These are used by the DefaultModelBinder to automatically validate your model objects when they are passed to action parameters.
</p>
<p>
I wanted to try and write one of these for <a href="http://fluentvalidation.codeplex.com">FluentValidation</a> (see <a href="http://www.jeremyskinner.co.uk/2009/12/20/fluentvalidation-moved-to-github-and-whats-coming-in-v1-2/">this post</a>) but after trying this it has become quite clear that the ModelValidatorProvider API does have some limitations which have caused me some problems.
</p>
<h3>Problem 1: Property-level validation</h3>
<p>
To understand this problem, first we need to look at how different validation frameworks perform their work.
</p>
<p>
When using FluentValidation, the validators work against a pre-populated object. For example:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> CustomerValidator <span style="color: #008000;">:</span> AbstractValidator<span style="color: #008000;">&lt;</span>Customer<span style="color: #000000;">&#123;</span> 
  <span style="color: #0600FF;">public</span> CustomerValidator<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
     RuleFor<span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Surname</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">NotNull</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
     RuleFor<span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">CreditLimit</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">GreaterThanOrEqualTo</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
var customer <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Customer <span style="color: #000000;">&#123;</span> CreditLimit <span style="color: #008000;">=</span> <span style="color: #008000;">-</span><span style="color: #FF0000;">1</span>, Surname <span style="color: #008000;">=</span> <span style="color: #0600FF;">null</span> <span style="color: #000000;">&#125;</span><span style="color: #008000;">;</span>
var validator <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> CustomerValidator<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
var results <span style="color: #008000;">=</span> validator.<span style="color: #0000FF;">Validate</span><span style="color: #000000;">&#40;</span>customer<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>
You cannot reliably validate individual properties by themselves because they may have dependencies on *other* properties being set. For example:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">RuleFor<span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Surname</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">NotEqual</span><span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Forename</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>
This rule says tht the Surname and Forename properties must not be equal. In this case, you cannot validate the surname property by itself without having first set the value for the Forename property. Other validation frameworks (eg the Castle Project&#8217;s validation attributes) work in a similar way.
</p>
<p>
The MVC Framework&#8217;s DefaultModelBinder is primarily designed to work with the System.ComponentModel.DataAnnotations attributes. These work in a different way &#8211; they validate individual values, not the entire object.  To support this, the DefaultModelBinder allows validating both the individual property values (in the OnPropertyValidated method) as well as validating the entire instance (in the OnModelUpdated method).
</p>
<p>
Here are the relevant methods from DefaultModelBinder:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">//OnPropertyValidated - called for each property being bound.</span>
<span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">virtual</span> <span style="color: #0600FF;">void</span> OnPropertyValidated<span style="color: #000000;">&#40;</span>ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, <span style="color: #FF0000;">object</span> value<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
    ModelMetadata propertyMetadata <span style="color: #008000;">=</span> bindingContext.<span style="color: #0000FF;">PropertyMetadata</span><span style="color: #000000;">&#91;</span>propertyDescriptor.<span style="color: #0000FF;">Name</span><span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span>
    propertyMetadata.<span style="color: #0000FF;">Model</span> <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span>
    <span style="color: #FF0000;">string</span> modelStateKey <span style="color: #008000;">=</span> CreateSubPropertyName<span style="color: #000000;">&#40;</span>bindingContext.<span style="color: #0000FF;">ModelName</span>, propertyMetadata.<span style="color: #0000FF;">PropertyName</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// run validation</span>
    <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>ModelValidator validator <span style="color: #0600FF;">in</span> propertyMetadata.<span style="color: #0000FF;">GetValidators</span><span style="color: #000000;">&#40;</span>controllerContext<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>ModelValidationResult validationResult <span style="color: #0600FF;">in</span> validator.<span style="color: #0000FF;">Validate</span><span style="color: #000000;">&#40;</span>bindingContext.<span style="color: #0000FF;">Model</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
            bindingContext.<span style="color: #0000FF;">ModelState</span>.<span style="color: #0000FF;">AddModelError</span><span style="color: #000000;">&#40;</span>CreateSubPropertyName<span style="color: #000000;">&#40;</span>modelStateKey, validationResult.<span style="color: #0000FF;">MemberName</span><span style="color: #000000;">&#41;</span>, validationResult.<span style="color: #0000FF;">Message</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// only add a &quot;value was required&quot; error message if there were no validation errors</span>
    <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>bindingContext.<span style="color: #0000FF;">ModelState</span>.<span style="color: #0000FF;">IsValidField</span><span style="color: #000000;">&#40;</span>modelStateKey<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>value <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span> <span style="color: #008000;">&amp;&amp;</span> <span style="color: #008000;">!</span>TypeHelpers.<span style="color: #0000FF;">TypeAllowsNullValue</span><span style="color: #000000;">&#40;</span>propertyDescriptor.<span style="color: #0000FF;">PropertyType</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
            bindingContext.<span style="color: #0000FF;">ModelState</span>.<span style="color: #0000FF;">AddModelError</span><span style="color: #000000;">&#40;</span>modelStateKey, GetValueRequiredResource<span style="color: #000000;">&#40;</span>controllerContext<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">//OnModelUpdated - called once the entire object has been bound. </span>
<span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">virtual</span> <span style="color: #0600FF;">void</span> OnModelUpdated<span style="color: #000000;">&#40;</span>ControllerContext controllerContext, ModelBindingContext bindingContext<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
    IDataErrorInfo errorProvider <span style="color: #008000;">=</span> bindingContext.<span style="color: #0000FF;">Model</span> <span style="color: #0600FF;">as</span> IDataErrorInfo<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>errorProvider <span style="color: #008000;">!=</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
         <span style="color: #FF0000;">string</span> errorText <span style="color: #008000;">=</span> errorProvider.<span style="color: #0000FF;">Error</span><span style="color: #008000;">;</span>
         <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #008000;">!</span><span style="color: #FF0000;">String</span>.<span style="color: #0000FF;">IsNullOrEmpty</span><span style="color: #000000;">&#40;</span>errorText<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
            bindingContext.<span style="color: #0000FF;">ModelState</span>.<span style="color: #0000FF;">AddModelError</span><span style="color: #000000;">&#40;</span>bindingContext.<span style="color: #0000FF;">ModelName</span>, errorText<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
          <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #008000;">!</span>IsModelValid<span style="color: #000000;">&#40;</span>bindingContext<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
        return<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>ModelValidator validator <span style="color: #0600FF;">in</span> bindingContext.<span style="color: #0000FF;">ModelMetadata</span>.<span style="color: #0000FF;">GetValidators</span><span style="color: #000000;">&#40;</span>controllerContext<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>ModelValidationResult validationResult <span style="color: #0600FF;">in</span> validator.<span style="color: #0000FF;">Validate</span><span style="color: #000000;">&#40;</span><span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
            bindingContext.<span style="color: #0000FF;">ModelState</span>.<span style="color: #0000FF;">AddModelError</span><span style="color: #000000;">&#40;</span>CreateSubPropertyName<span style="color: #000000;">&#40;</span>bindingContext.<span style="color: #0000FF;">ModelName</span>, validationResult.<span style="color: #0000FF;">MemberName</span><span style="color: #000000;">&#41;</span>, validationResult.<span style="color: #0000FF;">Message</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
On first glance, this looks like it will work. When OnPropertyValidated calls GetValidators, I can return an empty collection of validators and do all of my work in a single validator in OnModelUpdated. Unfortunately, this does not work.
</p>
<p>
See the end of OnPropertyValidated? Here, it checks if there have been any validation errors for the property and if not then it <strong>will go ahead and run its own built-in field validation anyway for non-nullable value types</strong> &#8211; it will put a message saying &#8220;A value was required&#8221; into ModelState. And you can&#8217;t turn this off. The *only way* to stop this built-in validation is to support property-level validation in your custom ValidatorProvider. Not very useful if the underlying framework does not support this.
</p>
<p>
To work around the above issue, I ended up adding property-level validation to FluentValidation, but this is not a completely reliable solution because of the issues related to cross-property validation I mentioned above.
</p>
<h3>Problem 2: The DataAnnotationsModelValidatorProvider is greedy</h3>
<p>
The next problem that I ran into is that the DataAnnotationsModelValidatorProvider will always run required field validation, even if you&#8217;re not using the DataAnnotations attributes!
</p>
<p>Here is an example that uses FluentValidation to validate an object where a null value is being bound to a non-nullable value type:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>Validator<span style="color: #000000;">&#40;</span><span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span>FooValidator<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> Foo <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> Id <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> FooValidator <span style="color: #008000;">:</span> AbstractValidator<span style="color: #008000;">&lt;</span>Foo<span style="color: #008000;">&gt;</span> <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> FooValidator<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		RuleFor<span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Id</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">NotEmpty</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #000000;">&#91;</span>Test<span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> AddsOneError<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
	var foo <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Foo<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	ModelValidatorProviders.<span style="color: #0000FF;">Providers</span>.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>
		<span style="color: #008000;">new</span> FluentValidationModelValidatorProvider<span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> AttributedValidatorFactory<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
	<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	var meta <span style="color: #008000;">=</span> ModelMetadataProviders.<span style="color: #0000FF;">Current</span>.<span style="color: #0000FF;">GetMetadataForProperty</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">=&gt;</span> <span style="color: #0600FF;">null</span>, <span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span>Foo<span style="color: #000000;">&#41;</span>, <span style="color: #666666;">&quot;Id&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	var validators <span style="color: #008000;">=</span> ModelValidatorProviders.<span style="color: #0000FF;">Providers</span>.<span style="color: #0000FF;">GetValidators</span><span style="color: #000000;">&#40;</span>meta, <span style="color: #008000;">new</span> ControllerContext<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	var results <span style="color: #008000;">=</span> validators.<span style="color: #0000FF;">SelectMany</span><span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Validate</span><span style="color: #000000;">&#40;</span>foo<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">ToList</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">1</span>, results.<span style="color: #0000FF;">Count</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">//fails - 2 instead of 1</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
This test fails because there are two error messages rather than one:
</p>
<pre>The Id field is required.
'Id' should not be empty.
</pre>
<p>
&#8230;the first of these errors comes from the DataAnnotationsModelValidatorProvider <strong>even though I have NOT decorated the Id property with a [Required] attribute</strong>.
</p>
<p>
Why does this happen? The answer is in DataAnnotationsModelValidatorProvider&#8217;s GetValidators method:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"> <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>metadata.<span style="color: #0000FF;">IsRequired</span> <span style="color: #008000;">&amp;&amp;</span> <span style="color: #008000;">!</span>attributes.<span style="color: #0000FF;">Any</span><span style="color: #000000;">&#40;</span>a <span style="color: #008000;">=&gt;</span> a <span style="color: #008000;">is</span> RequiredAttribute<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
       attributes <span style="color: #008000;">=</span> attributes.<span style="color: #0000FF;">Concat</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> <span style="color: #000000;">&#123;</span> <span style="color: #008000;">new</span> RequiredAttribute<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
 <span style="color: #000000;">&#125;</span></pre></div></div>

<p>
This checks to see if the property is a non-nullable type and it does not have a RequiredAttribute, <strong>then it assumes that the property should have a RequiredAttribute anyway!</strong><br />
You can work around this by removing the DataAnnotationsModelValidatorProvider:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">ModelValidatorProviders.<span style="color: #0000FF;">Providers</span>.<span style="color: #0000FF;">Clear</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
ModelValidatorProviders.<span style="color: #0000FF;">Providers</span>.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>
	<span style="color: #008000;">new</span> FluentValidationModelValidatorProvider<span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> AttributedValidatorFactory<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>
&#8230;and the test now passes.
</p>
<p>
Unfortunately, this is far from ideal. This means you cannot use the DataAnnotations attributes to validate one model and a custom provider for a different model. You have to choose one or the other.
</p>
<p>
One way to work around this problem is to use a composite validator provider that wraps the underlying providers:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> CompositeValidatorProvider <span style="color: #008000;">:</span> ModelValidatorProvider <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Bootstrap<span style="color: #000000;">&#40;</span>ModelValidatorProviderCollection providerCollection, <span style="color: #0600FF;">params</span> ModelValidatorProvider<span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> customProviders<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		var validators <span style="color: #008000;">=</span> customProviders.<span style="color: #0000FF;">ToList</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
		validators.<span style="color: #0000FF;">AddRange</span><span style="color: #000000;">&#40;</span>providerCollection<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
		providerCollection.<span style="color: #0000FF;">Clear</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
		providerCollection.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> CompositeValidatorProvider<span style="color: #000000;">&#40;</span>validators<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF;">readonly</span> IEnumerable<span style="color: #008000;">&lt;</span>ModelValidatorProvider<span style="color: #008000;">&gt;</span> innerInnerProviders<span style="color: #008000;">;</span>
&nbsp;
	<span style="color: #0600FF;">protected</span> CompositeValidatorProvider<span style="color: #000000;">&#40;</span>IEnumerable<span style="color: #008000;">&lt;</span>ModelValidatorProvider<span style="color: #008000;">&gt;</span> innerProviders<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">innerInnerProviders</span> <span style="color: #008000;">=</span> innerProviders<span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> IEnumerable<span style="color: #008000;">&lt;</span>ModelValidator<span style="color: #008000;">&gt;</span> GetValidators<span style="color: #000000;">&#40;</span>ModelMetadata metadata, ControllerContext context<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">foreach</span><span style="color: #000000;">&#40;</span>var provider <span style="color: #0600FF;">in</span> innerInnerProviders<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
			var validators <span style="color: #008000;">=</span> provider.<span style="color: #0000FF;">GetValidators</span><span style="color: #000000;">&#40;</span>metadata, context<span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">ToList</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
			<span style="color: #0600FF;">if</span><span style="color: #000000;">&#40;</span>validators.<span style="color: #0000FF;">Count</span> <span style="color: #008000;">&gt;</span> <span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
				<span style="color: #0600FF;">return</span> validators<span style="color: #008000;">;</span>	
			<span style="color: #000000;">&#125;</span>
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0600FF;">return</span> Enumerable.<span style="color: #0000FF;">Empty</span><span style="color: #008000;">&lt;</span>ModelValidator<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>This custom provider can be used to wrap the built-in providers (including the DataAnnotations provider) as well as your own custom providers. In its GetValidators method, it iterates over each of the inner providers and asks each one to create a collection of validators. <strong>It only returns validators from the first provider that returns a non-empty collection</strong>. This means that if your custom provider can validate the object then the DataAnnotations provider will not be executed.</p>
<p>
Now, the following test passes:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>Test<span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> AddsOneError<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
	var foo <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Foo<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    	var fluentProvider <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> FluentValidationModelValidatorProvider<span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> AttributedValidatorFactory<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	CompositeValidatorProvider.<span style="color: #0000FF;">Bootstrap</span><span style="color: #000000;">&#40;</span>ModelValidatorProviders.<span style="color: #0000FF;">Providers</span>, fluentProvider<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	var meta <span style="color: #008000;">=</span> ModelMetadataProviders.<span style="color: #0000FF;">Current</span>.<span style="color: #0000FF;">GetMetadataForProperty</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">=&gt;</span> <span style="color: #0600FF;">null</span>, <span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span>Foo<span style="color: #000000;">&#41;</span>, <span style="color: #666666;">&quot;Id&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	var validators <span style="color: #008000;">=</span> ModelValidatorProviders.<span style="color: #0000FF;">Providers</span>.<span style="color: #0000FF;">GetValidators</span><span style="color: #000000;">&#40;</span>meta, <span style="color: #008000;">new</span> ControllerContext<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	var results <span style="color: #008000;">=</span> validators.<span style="color: #0000FF;">SelectMany</span><span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Validate</span><span style="color: #000000;">&#40;</span>foo<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">ToList</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">1</span>, results.<span style="color: #0000FF;">Count</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
This raises the question: <strong>if you have to resort to doing this, what is the point in allowing multiple validation providers to be registered in the first place?</strong>
</p>
<p>
I am really hoping that the MVC team will fix this fairly significant problem before RTM, but as MVC2 is already at the RC stage I think this will be unlikely.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeremyskinner.co.uk/2010/01/13/limitations-of-mvc2s-modelvalidatorproviders/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>FluentValidation moved to GitHub and what&#8217;s coming in v1.2</title>
		<link>http://www.jeremyskinner.co.uk/2009/12/20/fluentvalidation-moved-to-github-and-whats-coming-in-v1-2/</link>
		<comments>http://www.jeremyskinner.co.uk/2009/12/20/fluentvalidation-moved-to-github-and-whats-coming-in-v1-2/#comments</comments>
		<pubDate>Sun, 20 Dec 2009 22:19:18 +0000</pubDate>
		<dc:creator>Jeremy Skinner</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[FluentValidation]]></category>

		<guid isPermaLink="false">http://www.jeremyskinner.co.uk/?p=265</guid>
		<description><![CDATA[After several months of increasing frustration with CodePlex&#8217;s svn integration, I have moved the source code for FluentValidation to GitHub. Continuous builds can still be downloaded from my build server. Documentation, discussions and the issue tracker will still remain on the CodePlex site, but if you want to play with the source code then you&#8217;ll [...]]]></description>
			<content:encoded><![CDATA[<p>After several months of increasing frustration with <a href="http://www.codeplex.com/">CodePlex&#8217;s</a> svn integration, I have moved the source code for <a href="http://fluentvalidation.codeplex.com">FluentValidation</a> to <a href="http://github.com/JeremySkinner/FluentValidation">GitHub</a>.</p>
<p>
Continuous builds can still be downloaded <a href="http://build.jeremyskinner.co.uk">from my build server.</a>
</p>
<p>
Documentation, discussions and the issue tracker will still remain on the CodePlex site, but if you want to play with the source code then you&#8217;ll need to <a href="http://github.com/JeremySkinner/FluentValidation">head over to GitHub</a> instead. If you have not used Git before then I recommend reading my <a href="http://mvccontrib.github.com/MvcContrib/">Git Guide</a> (the guide was written for the MvcContrib project, but all the concepts apply to FluentValidation too).
</p>
<h2>What&#8217;s coming with v1.2?</h2>
<p>
The upcoming release of FluentValidation (v1.2) will have several changes including the following:
</p>
<h3>A custom ModelMetadataProvider</h3>
<p>
The FluentValidationModelMetadataProvider will allow you to define ASP.NET MVC Metadata inside your validator classes, eg:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> CustomerValidator<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
   RuleFor<span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Surname</span><span style="color: #000000;">&#41;</span>
      .<span style="color: #0000FF;">NotNull</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008080; font-style: italic;">//regular validator</span>
      .<span style="color: #0000FF;">UIHint</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Surname&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">//MVC Metadata</span>
&nbsp;
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
The FluentValidationModelMetadataProvider will support the following metadata-related extension methods:</p>
<ul>
<li>HiddenInput</li>
<li>UIHint</li>
<li>Scaffold</li>
<li>DataType</li>
<li>DisplayName</li>
<li>DisplayFormat</li>
<li>ReadOnly</li>
</ul>
<h3>A custom ModelValidatorProvider</h3>
<p>
Previous versions of FluentValidation had a custom IModelBinder implementation that allowed you to use FluentValidation to validate ASP.NET MVC action parameters. This will no longer be necessary in v1.2 as ASP.NET MVC 2&#8242;s ModelValidatorProvider infrastructure means FluentValidation can now be plugged in to MVC&#8217;s DefaultModelBinder:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> MvcApplication <span style="color: #008000;">:</span> HttpApplication <span style="color: #000000;">&#123;</span>
   <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Application_Start<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
      RegisterRoutes<span style="color: #000000;">&#40;</span>RouteTable.<span style="color: #0000FF;">Routes</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
      ModelValidatorProviders.<span style="color: #0000FF;">Providers</span>.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> FluentValidationModelValidatorProvider<span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> AttributedValidatorFactory<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
   <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
Note that the FluentValidationModelValidatorProvider will only support server-side validation, not client-side validation. FluentValidation&#8217;s validation mechanism is not compatible with how ASP.NET MVC 2 generates clientside validation rules.
</p>
<h3>Customisable Validator Cascade Mode</h3>
<p>
The validator cascade mode will be customisable in v1.2. Currently, if you have multiple validators defined on a single property then all of those validators will be executed even if the first one fails. This can be changed by calling the Cascade method:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">RuleFor<span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Surname</span><span style="color: #000000;">&#41;</span>
  .<span style="color: #0000FF;">Cascade</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">StopOnFirstFailure</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
  .<span style="color: #0000FF;">NotNull</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
  .<span style="color: #0000FF;">Length</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">1</span>, <span style="color: #FF0000;">250</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>
In this case, the Length validator would not be run on the Surname property if the NotNull validator fails.
</p>
<p>
This will also be customisable globally by setting the static property ValidatorOptions.CascadeMode.
</p>
<p>
I hope to release a first beta of v1.2 in the next couple of weeks. The final release should coincide with the release of ASP.NET MVC 2.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeremyskinner.co.uk/2009/12/20/fluentvalidation-moved-to-github-and-whats-coming-in-v1-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Lambda Abuse: The MvcContrib Hash</title>
		<link>http://www.jeremyskinner.co.uk/2009/12/02/lambda-abuse-the-mvccontrib-hash/</link>
		<comments>http://www.jeremyskinner.co.uk/2009/12/02/lambda-abuse-the-mvccontrib-hash/#comments</comments>
		<pubDate>Wed, 02 Dec 2009 20:44:59 +0000</pubDate>
		<dc:creator>Jeremy Skinner</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.jeremyskinner.co.uk/?p=255</guid>
		<description><![CDATA[There&#8217;s recently been a lot of discussion on this post on StackOverflow about the use of lambda expressions to build dictionaries as part of the MvcContrib grid. The Grid API allows you to define HTML attributes for a table by chaining a call to the &#8216;Attributes&#8217; method as part of a grid definition: &#60;%= Html.Grid&#40;Model.People&#41;.Columns&#40;column [...]]]></description>
			<content:encoded><![CDATA[<p>
There&#8217;s recently been a lot of discussion on <a href="http://stackoverflow.com/questions/1718037/abuse-of-c-lambda-expressions-or-syntax-brilliance">this post on StackOverflow</a> about the use of lambda expressions to build dictionaries as part of the <a href="http://www.jeremyskinner.co.uk/2009/02/22/rewriting-the-mvccontrib-grid-part-2-new-syntax/">MvcContrib grid</a>.
</p>
<p>
The Grid API allows you to define HTML attributes for a table by chaining a call to the &#8216;Attributes&#8217; method as part of a grid definition:
</p>

<div class="wp_syntax"><div class="code"><pre class="asp" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;%</span><span style="color: #006600; font-weight: bold;">=</span> Html.<span style="color: #9900cc;">Grid</span><span style="color: #006600; font-weight:bold;">&#40;</span>Model.<span style="color: #9900cc;">People</span><span style="color: #006600; font-weight:bold;">&#41;</span>.<span style="color: #9900cc;">Columns</span><span style="color: #006600; font-weight:bold;">&#40;</span>column <span style="color: #006600; font-weight: bold;">=&gt;</span> <span style="color: #006600; font-weight:bold;">&#123;</span>
     		column.<span style="color: #990099; font-weight: bold;">For</span><span style="color: #006600; font-weight:bold;">&#40;</span>x <span style="color: #006600; font-weight: bold;">=&gt;</span> x.<span style="color: #9900cc;">Id</span><span style="color: #006600; font-weight:bold;">&#41;</span><span style="color: #006600; font-weight: bold;">;</span>
     		column.<span style="color: #990099; font-weight: bold;">For</span><span style="color: #006600; font-weight:bold;">&#40;</span>x <span style="color: #006600; font-weight: bold;">=&gt;</span> x.<span style="color: #9900cc;">Name</span><span style="color: #006600; font-weight:bold;">&#41;</span><span style="color: #006600; font-weight: bold;">;</span>
     		column.<span style="color: #990099; font-weight: bold;">For</span><span style="color: #006600; font-weight:bold;">&#40;</span>x <span style="color: #006600; font-weight: bold;">=&gt;</span> x.<span style="color: #9900cc;">DateOfBirth</span><span style="color: #006600; font-weight:bold;">&#41;</span><span style="color: #006600; font-weight: bold;">;</span>
<span style="color: #006600; font-weight:bold;">&#125;</span><span style="color: #006600; font-weight:bold;">&#41;</span>
.<span style="color: #9900cc;">Attributes</span><span style="color: #006600; font-weight:bold;">&#40;</span>style <span style="color: #006600; font-weight: bold;">=&gt;</span> <span style="color: #cc0000;">&quot;width:100%&quot;</span>, cellpadding <span style="color: #006600; font-weight: bold;">=&gt;</span> <span style="color: #800000;">0</span><span style="color: #006600; font-weight:bold;">&#41;</span>
 <span style="color: #000000; font-weight: bold;">%&gt;</span></pre></div></div>

<p>
This makes use of the <a href="http://mvccontrib.codeplex.com/sourcecontrol/network/Show?projectName=MVCContrib&#038;changeSetId=877a66c13756#src%2fMVCContrib%2fHash.cs">MvcContrib.Hash class</a> to construct an IDictionary from lambda expressions. So the following Hash definiton&#8230;:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var hash <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Hash<span style="color: #000000;">&#40;</span>foo <span style="color: #008000;">=&gt;</span> <span style="color: #666666;">&quot;bar&quot;</span>, baz <span style="color: #008000;">=&gt;</span> <span style="color: #666666;">&quot;blah&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>&#8230;is the equivalent of:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var hash <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Dictionary<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span>, <span style="color: #FF0000;">object</span><span style="color: #008000;">&gt;</span> 
<span style="color: #000000;">&#123;</span>
   <span style="color: #000000;">&#123;</span> <span style="color: #666666;">&quot;foo&quot;</span>, <span style="color: #666666;">&quot;bar&quot;</span> <span style="color: #000000;">&#125;</span>,
   <span style="color: #000000;">&#123;</span> <span style="color: #666666;">&quot;baz&quot;</span>, <span style="color: #666666;">&quot;blah&quot;</span> <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span><span style="color: #008000;">;</span></pre></div></div>

<p>
Internally, this is achieved by using a technique I first saw on <a href="http://blog.bittercoder.com/PermaLink,guid,206e64d1-29ae-4362-874b-83f5b103727f.aspx">Alex Henderson&#8217;s blog</a>. By taking an array of delegates, it is possible to capture the compile-time variable names used by the lambda expressions and use them as keys for the dictionary.
</p>
<p>
The responses to this approach have been quite polarized. There has been lots of positive feedback on twitter&#8230;
</p>
<blockquote><p>
&#8220;@JeremySkinner I like it, no problem for me, infact I&#8217;ll apply this technique where ever I can from now one forward <img src='http://www.jeremyskinner.co.uk/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> &#8221; (from <a href="http://twitter.com/marknijhof">Mark Nijhof</a>)
</p></blockquote>
<blockquote><p>
&#8220;@JeremySkinner the lambda abuse is awesome, very ruby symbols like, and pushing the language envelope.&#8221; (from <a href="http://twitter.com/AdamTybor">Adam Tybor</a>)
</p></blockquote>
<p>
&#8230;and also in the blogosphere (eg <a href="http://odetocode.com/Blogs/scott/archive/2009/11/30/your-abomination-is-my-clever-hack.aspx">here</a> and <a href="http://www.corebvba.be/blog/post/Rant-Your-abomination-is-my-clever-hack.aspx">here</a>) as well as on the StackOverflow post.
</p>
<p>
There has also been a lot of negative feedback:
</p>
<blockquote><p>
&#8220;I hardly ever came across this kind of usage. I think it&#8217;s inappropriate&#8221;
</p></blockquote>
<blockquote><p>
&#8220;I find that odd not so much because of the name, but because the lambda is unnecessary; it could use an anonymous-type and be more flexible&#8221;
</p></blockquote>
<blockquote><p>
&#8220;This is horrible on more than one level. And no, this is nothing like Ruby its an abuse of C# and .Net. &#8221;
</p></blockquote>
<blockquote><p>
&#8220;It&#8217;s counter-intuitive, there is no way of just looking at the code to figure out what it does.&#8221;
</p></blockquote>
<p>
Interestingly, some of the most negative comments were from <a href="http://blogs.msdn.com/ericlippert/">Eric Lippert</a> on the C# compiler team:
</p>
<blockquote><p>
&#8220;This is horrid in so many ways.&#8221;
</p></blockquote>
<blockquote><p>
&#8220;I just asked Anders (and the rest of the design team) what they thought. Let&#8217;s just say the results would not be printable in a family-friendly newspaper&#8221;
</p></blockquote>
<p>
I thought Eric&#8217;s response was possibly a little harsh, but wanted to try and address and explain some of the issues here:
</p>
<h2>Issue #1: This is not interop friendly!</h2>
<p>
One of the issues raised was that this is <a href="http://stackoverflow.com/questions/1718037/abuse-of-c-lambda-expressions-or-syntax-brilliance/1718088#1718088">not interop friendly</a>. If, for example, you wanted to build a grid using F# (or possibly another CLR language) then this approach would not work as it is dependent on the C# compiler. This is a good point and is very true.
</p>
<p>
The thing I want to point out here is that the syntax is <strong>completely optional</strong>. This particular overload for the &#8216;Attributes&#8217; method on the grid is an extension method for convenience when using C#. The main implementation for this method takes an IDictionary. If you don&#8217;t like the abusive-lambda approach (or you can&#8217;t use it from another language) then you can use the &#8216;regular&#8217; overload instead:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">.<span style="color: #0000FF;">Attributes</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> Dictionary<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span>, <span style="color: #FF0000;">object</span><span style="color: #008000;">&gt;</span> <span style="color: #000000;">&#123;</span> <span style="color: #000000;">&#123;</span> <span style="color: #666666;">&quot;style&quot;</span>, <span style="color: #666666;">&quot;width:100%&quot;</span> <span style="color: #000000;">&#125;</span>, <span style="color: #000000;">&#123;</span> <span style="color: #666666;">&quot;cellpadding&quot;</span>, <span style="color: #FF0000;">0</span> <span style="color: #000000;">&#125;</span> <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span></pre></div></div>

<p>
The abusive-lambdas are merely a preference &#8211; I happen to like it as it saves me some keystrokes. If you don&#8217;t like it, don&#8217;t use it.
</p>
<h2>Issue #2: This is unintuitive and not intellisense-friendly</h2>
<p>
From a readability perspective, I do not agree that this is unintuitive. If you saw &#8220;Attributes(style =&gt; &#8220;width:100%&#8221;, cellpadding =&gt; 0)&#8221; in a grid definition then I think it&#8217;s pretty obvious what&#8217;s going on. It even looks like HTML attributes (kinda).
</p>
<p>
From an Intellisense perspective, I completely agree. If you see the following method signature, it is not immediately obvious what&#8217;s going on:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> IGridWithOptions<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span> Attributes<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #0600FF;">this</span> IGridWithOptions<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span> grid, <span style="color: #0600FF;">params</span> Func<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">object</span>, <span style="color: #FF0000;">object</span><span style="color: #008000;">&gt;</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> hash<span style="color: #000000;">&#41;</span></pre></div></div>

<p>
But hold on a second&#8230;let&#8217;s compare this to the approach that the ASP.NET MVC Framework uses for all its built-in HTML helpers:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> MvcHtmlString TextBox<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">this</span> HtmlHelper htmlHelper, <span style="color: #FF0000;">string</span> name, <span style="color: #FF0000;">object</span> value, <span style="color: #FF0000;">object</span> htmlAttributes<span style="color: #000000;">&#41;</span></pre></div></div>

<p>
Notice that &#8220;object htmlAttributes&#8221; at the end? That allows you to specify an anonymous type containing HTML attributes:
</p>

<div class="wp_syntax"><div class="code"><pre class="asp" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;%</span><span style="color: #006600; font-weight: bold;">=</span> Html.<span style="color: #9900cc;">TextBox</span><span style="color: #006600; font-weight:bold;">&#40;</span><span style="color: #cc0000;">&quot;foo&quot;</span>, <span style="color: #cc0000;">&quot;bar&quot;</span>, <span style="color: #0000ff; font-weight: bold;">new</span><span style="color: #006600; font-weight:bold;">&#123;</span> style <span style="color: #006600; font-weight: bold;">=</span> <span style="color: #cc0000;">&quot;width:100%&quot;</span>, <span style="color: #006600; font-weight: bold;">@</span><span style="color: #0000ff; font-weight: bold;">class</span><span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;foo&quot;</span> <span style="color: #006600; font-weight:bold;">&#125;</span><span style="color: #006600; font-weight:bold;">&#41;</span></pre></div></div>

<p>
This is <strong>just as opaque as using abusive lambdas.</strong> In fact, I&#8217;d aruge that it&#8217;s *more* opaque because the htmlAttributes parameter is defined as type object. This means you could accidentally pass *anything* in this parameter (eg a string) and the compiler would not complain. I have done this on many occasions and I find it very frustrating. At least with a parameter of type Func&lt;object, object&gt;[] you can&#8217;t accidentally pass in a string. (Much like the MvcContrib approach, ASP.NET MVC&#8217;s helpers also have overloads that take an IDictionary if you prefer).
</p>
<h2>Issue #3: You can achieve the same result with an anonymous type:</h2>
<p>
I don&#8217;t believe that the Hash is really any worse than the anonymous type. In fact, in some ways I think the use of an anonymous type is worse (see my point above regarding opacity)
</p>
<h2>Issue #4: Performance implications!</h2>
<p>
There seems to be some misunderstanding around the use of the lambda syntax. On the one hand you can use a lambda to define an expression tree which can then be parsed (this is how LINQ to SQL works &#8211; the expression tree is then converted to SQL). These expressions can then be compiled to a delegate and invoked which is an expensive operation. However, lambdas can also be used for anonymous methods. This is essentially syntactic sugar over a standard .NET delegate and is an improvement over C# 2&#8242;s <a href="http://msdn.microsoft.com/en-us/library/0yw3tz5k%28VS.80%29.aspx">anonymous delegate syntax</a>. </p>
<p>
The MvcContrib uses the latter approach to do its work. This way, there is no overhead for compiling the expressions. In fact, there is very little overhead versus using the standard Dictionary.Add method. Alex Henderson talks more about the different approaches for doing this <a href="http://blog.bittercoder.com/PermaLink,guid,206e64d1-29ae-4362-874b-83f5b103727f.aspx">on his blog</a>, but these were the results of his benchmark for 10000 calls:
</p>
<ul>
<li>Using Dictionary.Add: 10.0144ms</li>
<li>Using lambdas with expression compilation: 9713.968ms (240.3456ms with constants) </li>
<li><strong>Using lambdas as delegates: 30.0432ms</strong></strong></li>
</ul>
<h2>Issue #5: Why not use method chaining?</h2>
<p>
One suggestion was to chain multiple calls to &#8216;Attribute&#8217;:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">.<span style="color: #0000FF;">Attribute</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;style&quot;</span>, <span style="color: #666666;">&quot;width:100%&quot;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Attribute</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;cellpadding&quot;</span>, <span style="color: #666666;">&quot;0&quot;</span><span style="color: #000000;">&#41;</span></pre></div></div>

<p>
This definitely works, but the whole reason why I decided to use the Hash was because I want to mimimize the amount of typing (my fingers tire easily) and making multiple calls to &#8216;Attribute&#8217; is rather verbose.
</p>
<h2>And finally&#8230;</h2>
<p>
In the end, this is really just down to personal preference:</p>
<ul>
<li> I do not like C#&#8217;s dictionary initializers &#8211; I think they&#8217;re too verbose</li>
<li>I do not like the use of anonymous types as dictionaries as they require you to take parameters of type &#8220;object&#8221;</li>
</ul>
<p>The Abusive Lambda Pattern (I think that&#8217;s what I&#8217;ll call this) is just something I happen to like, but if you don&#8217;t like it then you certainly don&#8217;t have to use it.</p>
<p>Perhaps Eric and the C# team would like to give us a more succinct collection initializer for Dictionaries in C#5? <img src='http://www.jeremyskinner.co.uk/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  </p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeremyskinner.co.uk/2009/12/02/lambda-abuse-the-mvccontrib-hash/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
	</channel>
</rss>
