<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:copyright="http://blogs.law.harvard.edu/tech/rss" xmlns:image="http://purl.org/rss/1.0/modules/image/">
    <channel>
        <title>.NET 4.0</title>
        <link>http://geekswithblogs.net/michelotti/category/10976.aspx</link>
        <description>.NET 4.0</description>
        <language>en-US</language>
        <copyright>Steve Michelotti</copyright>
        <managingEditor>steve.michelotti@gmail.com</managingEditor>
        <generator>Subtext Version 0.0.0.0</generator>
        <item>
            <title>MVC 3 AdditionalMetadata Attribute with ViewBag to Render Dynamic UI</title>
            <link>http://geekswithblogs.net/michelotti/archive/2011/01/30/mvc-3-additionalmetadata-attribute-with-viewbag-to-render-dynamic-ui.aspx</link>
            <description>&lt;p&gt;A few months ago I blogged about using &lt;a href="http://geekswithblogs.net/michelotti/archive/2010/09/08/mvc-2-model-metadata-to-render-dynamic-ui.aspx" target="_blank"&gt;Model metadata to render a dynamic UI in MVC 2&lt;/a&gt;. The scenario in the post was that we might have a view model where the questions are conditionally displayed and therefore a dynamic UI is needed. To recap the previous post, the solution was to use a custom attribute called [QuestionId] in conjunction with an “ApplicableQuestions” collection to identify whether each question should be displayed. This allowed me to have a view model that looked like this:&lt;/p&gt; &lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;  &lt;div class="csharpcode"&gt;   &lt;pre&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;[UIHint(&lt;span class="str"&gt;"ScalarQuestion"&lt;/span&gt;)]&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   2:  &lt;/span&gt;[DisplayName(&lt;span class="str"&gt;"First Name"&lt;/span&gt;)]&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   3:  &lt;/span&gt;[QuestionId(&lt;span class="str"&gt;"NB0021"&lt;/span&gt;)]&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   4:  &lt;/span&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; FirstName { get; set; }&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   5:  &lt;/span&gt;        &lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   6:  &lt;/span&gt;[UIHint(&lt;span class="str"&gt;"ScalarQuestion"&lt;/span&gt;)]&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   7:  &lt;/span&gt;[DisplayName(&lt;span class="str"&gt;"Last Name"&lt;/span&gt;)]&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   8:  &lt;/span&gt;[QuestionId(&lt;span class="str"&gt;"NB0022"&lt;/span&gt;)]&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   9:  &lt;/span&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; LastName { get; set; }&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  10:  &lt;/span&gt; &lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  11:  &lt;/span&gt;[UIHint(&lt;span class="str"&gt;"ScalarQuestion"&lt;/span&gt;)]&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  12:  &lt;/span&gt;[QuestionId(&lt;span class="str"&gt;"NB0023"&lt;/span&gt;)]&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  13:  &lt;/span&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; Age { get; set; }&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  14:  &lt;/span&gt; &lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  15:  &lt;/span&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; IEnumerable&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; ApplicableQuestions { get; set; }&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;At the same time, I was able to avoid repetitive IF statements for every single question in my view:&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;

&lt;div class="csharpcode"&gt;
  &lt;pre&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;&lt;span class="asp"&gt;&amp;lt;%&lt;/span&gt;: Html.EditorFor(m =&amp;gt; m.FirstName, &lt;span class="kwrd"&gt;new&lt;/span&gt; { applicableQuestions = Model.ApplicableQuestions })&lt;span class="asp"&gt;%&amp;gt;&lt;/span&gt;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   2:  &lt;/span&gt;&lt;span class="asp"&gt;&amp;lt;%&lt;/span&gt;: Html.EditorFor(m =&amp;gt; m.LastName, &lt;span class="kwrd"&gt;new&lt;/span&gt; { applicableQuestions = Model.ApplicableQuestions })&lt;span class="asp"&gt;%&amp;gt;&lt;/span&gt;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   3:  &lt;/span&gt;&lt;span class="asp"&gt;&amp;lt;%&lt;/span&gt;: Html.EditorFor(m =&amp;gt; m.Age, &lt;span class="kwrd"&gt;new&lt;/span&gt; { applicableQuestions = Model.ApplicableQuestions })&lt;span class="asp"&gt;%&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;by creating an Editor Template called “ScalarQuestion” that encapsulated the IF statement:&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;

&lt;div class="csharpcode"&gt;
  &lt;pre&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;&lt;span class="asp"&gt;&amp;lt;%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %&amp;gt;&lt;/span&gt;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   2:  &lt;/span&gt;&lt;span class="asp"&gt;&amp;lt;%@ Import Namespace="DynamicQuestions.Models" %&amp;gt;&lt;/span&gt;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   3:  &lt;/span&gt;&lt;span class="asp"&gt;&amp;lt;%@ Import Namespace="System.Linq" %&amp;gt;&lt;/span&gt;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   4:  &lt;/span&gt;&lt;span class="asp"&gt;&amp;lt;%&lt;/span&gt; &lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   5:  &lt;/span&gt;    var applicableQuestions = &lt;span class="kwrd"&gt;this&lt;/span&gt;.ViewData[&lt;span class="str"&gt;"applicableQuestions"&lt;/span&gt;] &lt;span class="kwrd"&gt;as&lt;/span&gt; IEnumerable&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   6:  &lt;/span&gt;    var questionAttr = &lt;span class="kwrd"&gt;this&lt;/span&gt;.ViewData.ModelMetadata.ContainerType.GetProperty(&lt;span class="kwrd"&gt;this&lt;/span&gt;.ViewData.ModelMetadata.PropertyName).GetCustomAttributes(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(QuestionIdAttribute), &lt;span class="kwrd"&gt;true&lt;/span&gt;) &lt;span class="kwrd"&gt;as&lt;/span&gt; QuestionIdAttribute[];&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   7:  &lt;/span&gt;    &lt;span class="kwrd"&gt;string&lt;/span&gt; questionId = &lt;span class="kwrd"&gt;null&lt;/span&gt;;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   8:  &lt;/span&gt;    &lt;span class="kwrd"&gt;if&lt;/span&gt; (questionAttr.Length &amp;gt; 0)&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   9:  &lt;/span&gt;    {&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  10:  &lt;/span&gt;        questionId = questionAttr[0].Id;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  11:  &lt;/span&gt;    }&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  12:  &lt;/span&gt;    &lt;span class="kwrd"&gt;if&lt;/span&gt; (questionId != &lt;span class="kwrd"&gt;null&lt;/span&gt; &amp;amp;&amp;amp; applicableQuestions.Contains(questionId)) { &lt;span class="asp"&gt;%&amp;gt;&lt;/span&gt;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  13:  &lt;/span&gt;        &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;div&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  14:  &lt;/span&gt;            &lt;span class="asp"&gt;&amp;lt;%&lt;/span&gt;: Html.Label(&lt;span class="str"&gt;""&lt;/span&gt;) &lt;span class="asp"&gt;%&amp;gt;&lt;/span&gt;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  15:  &lt;/span&gt;            &lt;span class="asp"&gt;&amp;lt;%&lt;/span&gt;: Html.TextBox(&lt;span class="str"&gt;""&lt;/span&gt;, &lt;span class="kwrd"&gt;this&lt;/span&gt;.Model)&lt;span class="asp"&gt;%&amp;gt;&lt;/span&gt;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  16:  &lt;/span&gt;        &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;div&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  17:  &lt;/span&gt;&lt;span class="asp"&gt;&amp;lt;%&lt;/span&gt;  } &lt;span class="asp"&gt;%&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;You might want to go back and read the &lt;a href="http://geekswithblogs.net/michelotti/archive/2010/09/08/mvc-2-model-metadata-to-render-dynamic-ui.aspx" target="_blank"&gt;full post&lt;/a&gt; in order to get the full context.&lt;/p&gt;

&lt;p&gt;MVC 3 offers a couple of new features that make this scenario more elegant to implement. The first step is to use the new [&lt;a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.additionalmetadataattribute(v=vs.98).aspx" target="_blank"&gt;AdditionalMetadata&lt;/a&gt;] attribute which, so far, appears to be an under appreciated new feature of MVC 3. With this attribute, I don’t need my custom [QuestionId] attribute anymore - now I can just write my view model like this:&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;

&lt;div class="csharpcode"&gt;
  &lt;pre&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;[UIHint(&lt;span class="str"&gt;"ScalarQuestion"&lt;/span&gt;)]&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   2:  &lt;/span&gt;[DisplayName(&lt;span class="str"&gt;"First Name"&lt;/span&gt;)]&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   3:  &lt;/span&gt;[AdditionalMetadata(&lt;span class="str"&gt;"QuestionId"&lt;/span&gt;, &lt;span class="str"&gt;"NB0021"&lt;/span&gt;)]&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   4:  &lt;/span&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; FirstName { get; set; }&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   5:  &lt;/span&gt; &lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   6:  &lt;/span&gt;[UIHint(&lt;span class="str"&gt;"ScalarQuestion"&lt;/span&gt;)]&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   7:  &lt;/span&gt;[DisplayName(&lt;span class="str"&gt;"Last Name"&lt;/span&gt;)]&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   8:  &lt;/span&gt;[AdditionalMetadata(&lt;span class="str"&gt;"QuestionId"&lt;/span&gt;, &lt;span class="str"&gt;"NB0022"&lt;/span&gt;)]&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   9:  &lt;/span&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; LastName { get; set; }&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  10:  &lt;/span&gt; &lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  11:  &lt;/span&gt;[UIHint(&lt;span class="str"&gt;"ScalarQuestion"&lt;/span&gt;)]&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  12:  &lt;/span&gt;[AdditionalMetadata(&lt;span class="str"&gt;"QuestionId"&lt;/span&gt;, &lt;span class="str"&gt;"NB0023"&lt;/span&gt;)]&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  13:  &lt;/span&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; Age { get; set; }&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Thus far, the documentation seems to be pretty sparse on the AdditionalMetadata attribute. It’s buried in the &lt;a href="http://www.asp.net/mvc/mvc3#BM_Other_New_Features" target="_blank"&gt;Other New Features&lt;/a&gt; section of the MVC 3 home page and, after showing the attribute on a view model property, it just says, “&lt;strong&gt;This metadata is made available to any display or editor template when a product view model is rendered. It is up to you to interpret the metadata information&lt;/strong&gt;.” But what exactly does it look like for me to “interpret the metadata information”? Well, it turns out it makes the view much easier to work with. Here is the re-implemented ScalarQuestion template updated for MVC 3 and Razor:&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;

&lt;div class="csharpcode"&gt;
  &lt;pre&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;@{&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   2:  &lt;/span&gt;    object questionId;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   3:  &lt;/span&gt;    ViewData.ModelMetadata.AdditionalValues.TryGetValue("QuestionId", out questionId);&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   4:  &lt;/span&gt;    if (ViewBag.applicableQuestions.Contains((string)questionId)) { &lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   5:  &lt;/span&gt;        &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;div&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   6:  &lt;/span&gt;            @Html.LabelFor(m =&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt; m)&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   7:  &lt;/span&gt;            @Html.TextBoxFor(m =&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt; m)&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   8:  &lt;/span&gt;        &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;div&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   9:  &lt;/span&gt;    }&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  10:  &lt;/span&gt;}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;So we’ve gone from 17 lines of code (in the MVC 2 version) to about 7-8 lines of code here. The first thing to notice is that in MVC 3 we now have a property called “AdditionalValues” that hangs off of the ModelMetadata property. This is automatically populated by any [AdditionalMetadata] attributes on the property. There is no more need for me to explicitly write Reflection code to GetCustomAttributes() and then check to see if those attributes were present. I can just call TryGetValue() on the dictionary to see if they were present. Secondly, the “applicableQuestions” anonymous type that I passed in from the calling view – in MVC 3 I now have a dynamic ViewBag property where I can just “dot into” the applicableQuestions with a nicer syntax than dictionary square bracket syntax. And there’s no problems calling the Contains() method on this dynamic object because at runtime the DLR has resolved that it is a generic List&amp;lt;string&amp;gt;.&lt;/p&gt;

&lt;p&gt;At this point you might be saying that, yes the view got much nicer than the MVC 2 version, but my view model got slightly worse.  In the previous version I had a nice [QuestionId] attribute but now, with the [AdditionalMetadata] attribute, I have to type the string “QuestionId” for every single property and hope that I don’t make a typo. Well, the good news is that it’s easy to create your own attributes that can participate in the metadata’s additional values. The key is that the attribute must implement that &lt;a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.imetadataaware(v=vs.98).aspx" target="_blank"&gt;IMetadataAware&lt;/a&gt; interface and populate the AdditionalValues dictionary in the OnMetadataCreated() method:&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;

&lt;div class="csharpcode"&gt;
  &lt;pre&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; QuestionIdAttribute : Attribute, IMetadataAware&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   2:  &lt;/span&gt;{&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   3:  &lt;/span&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; Id { get; set; }&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   4:  &lt;/span&gt; &lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   5:  &lt;/span&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; QuestionIdAttribute(&lt;span class="kwrd"&gt;string&lt;/span&gt; id)&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   6:  &lt;/span&gt;    {&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   7:  &lt;/span&gt;        &lt;span class="kwrd"&gt;this&lt;/span&gt;.Id = id;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   8:  &lt;/span&gt;    }&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   9:  &lt;/span&gt; &lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  10:  &lt;/span&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; OnMetadataCreated(ModelMetadata metadata)&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  11:  &lt;/span&gt;    {&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  12:  &lt;/span&gt;        metadata.AdditionalValues[&lt;span class="str"&gt;"QuestionId"&lt;/span&gt;] = &lt;span class="kwrd"&gt;this&lt;/span&gt;.Id;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  13:  &lt;/span&gt;    }&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  14:  &lt;/span&gt;}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;This now allows me to encapuslate my “QuestionId” string in just one place and get back to my original attribute which can be used like this: [QuestionId(“NB0021”)].&lt;/p&gt;

&lt;p&gt;The [AdditionalMetadata] attribute is a powerful and under-appreciated new feature of MVC 3. Combined with the dynamic ViewBag property, you can do some really interesting things with your applications with less code and ceremony.&lt;/p&gt; &lt;img src="http://geekswithblogs.net/michelotti/aggbug/143710.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Steve Michelotti</dc:creator>
            <guid>http://geekswithblogs.net/michelotti/archive/2011/01/30/mvc-3-additionalmetadata-attribute-with-viewbag-to-render-dynamic-ui.aspx</guid>
            <pubDate>Mon, 31 Jan 2011 04:44:35 GMT</pubDate>
            <wfw:comment>http://geekswithblogs.net/michelotti/comments/143710.aspx</wfw:comment>
            <comments>http://geekswithblogs.net/michelotti/archive/2011/01/30/mvc-3-additionalmetadata-attribute-with-viewbag-to-render-dynamic-ui.aspx#feedback</comments>
            <slash:comments>2</slash:comments>
            <wfw:commentRss>http://geekswithblogs.net/michelotti/comments/commentRss/143710.aspx</wfw:commentRss>
            <trackback:ping>http://geekswithblogs.net/michelotti/services/trackbacks/143710.aspx</trackback:ping>
        </item>
        <item>
            <title>WCF REST Services Inside MVC Projects</title>
            <link>http://geekswithblogs.net/michelotti/archive/2010/09/22/wcf-rest-services-inside-mvc-projects.aspx</link>
            <description>&lt;p&gt;Recently I blogged about &lt;a href="http://geekswithblogs.net/michelotti/archive/2010/08/21/restful-wcf-services-with-no-svc-file-and-no-config.aspx" target="_blank"&gt;WCF REST services with no svc file and no config&lt;/a&gt;. In this post I also discussed the pros/cons of WCF services as compared to using MVC controller actions for web services and I made the case that, in many instances, WCF REST services is better than using the MVC infrastructure because WCF provides:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;a more RESTful API with less work &lt;/li&gt;    &lt;li&gt;a convenient automatic help page to assist consumers of your service &lt;/li&gt;    &lt;li&gt;automatic format selection (i.e., xml/json) depending on HTTP headers &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;In any case, using both WCF REST services and MVC-style web services are *both* quite convenient – and you don’t have to choose. You can use both. In fact, you can use both inside the same web application project. However, a &lt;a href="http://stackoverflow.com/q/3570887/352246" target="_blank"&gt;recent question on StackOverflow&lt;/a&gt; illustrates that you have to be careful how you set up your routing in order to make WCF REST services work inside MVC applications.&lt;/p&gt;  &lt;p&gt;If you &lt;a href="http://stackoverflow.com/q/3570887/352246" target="_blank"&gt;have a look at the question on StackOverflow&lt;/a&gt;, you’ll see the routes were originally set up like this:&lt;/p&gt; &lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;  &lt;div class="csharpcode"&gt;   &lt;pre&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;routes.IgnoreRoute(&lt;span class="str"&gt;"{resource}.axd/{*pathInfo}"&lt;/span&gt;);&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   2:  &lt;/span&gt;            &lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   3:  &lt;/span&gt;routes.Add(&lt;span class="kwrd"&gt;new&lt;/span&gt; ServiceRoute(&lt;span class="str"&gt;"Person"&lt;/span&gt;, &lt;span class="kwrd"&gt;new&lt;/span&gt; WebServiceHostFactory(), &lt;span class="kwrd"&gt;typeof&lt;/span&gt;(PersonService)));&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   4:  &lt;/span&gt; &lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   5:  &lt;/span&gt;routes.MapRoute(&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   6:  &lt;/span&gt;    &lt;span class="str"&gt;"Default"&lt;/span&gt;, &lt;span class="rem"&gt;// Route name&lt;/span&gt;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   7:  &lt;/span&gt;    &lt;span class="str"&gt;"{controller}/{action}/{id}"&lt;/span&gt;, &lt;span class="rem"&gt;// URL with parameters&lt;/span&gt;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   8:  &lt;/span&gt;    &lt;span class="kwrd"&gt;new&lt;/span&gt; { controller = &lt;span class="str"&gt;"Home"&lt;/span&gt;, action = &lt;span class="str"&gt;"Index"&lt;/span&gt;, id = UrlParameter.Optional } &lt;span class="rem"&gt;// Parameter defaults&lt;/span&gt;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   9:  &lt;/span&gt;);&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;The service route was for the WCF Service (using no *.svc file) and the last route was the standard MVC route. In most of the cases this works fine. Navigation to the root correctly lands on the HomeController’s Index method. Navigation to “/Person/help” correctly goes to the WCF REST help page and the WCF REST service can be invoked just fine. However, the action links were not correct.  When formulating a simple action link like this:&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;

&lt;div class="csharpcode"&gt;
  &lt;pre&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;&lt;span class="asp"&gt;&amp;lt;%&lt;/span&gt;: Html.ActionLink(&lt;span class="str"&gt;"Home"&lt;/span&gt;, &lt;span class="str"&gt;"Index"&lt;/span&gt;, &lt;span class="str"&gt;"Home"&lt;/span&gt;)&lt;span class="asp"&gt;%&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;The resulting URL being produced was: &lt;strong&gt;“/Person?action=Index&amp;amp;controller=Home”&lt;/strong&gt; which was clearly not correct. It’s hitting the first route and thinking it should just put “Person” for the first segment. It then cannot match the “controller” or “action” tokens so it just puts them in the query string. It will attempt to go to the service but the URI is incorrect so, if it’s a WCF REST service, you’ll just get the default help page.&lt;/p&gt;

&lt;p&gt;Of course, we know that the *order* matters for routing so what if we put the MVC route first and the service route second? In this case, we run into a different problem. If the first URI segment is “Person” then it will try to match that as the controller name and you’ll get a 404 or, if you’re using a controller factory, your IoC container won’t be able to find a controller named “PersonController”.&lt;/p&gt;

&lt;p&gt;So how can we get the WCF REST service route and the MVC routes to play nice with each other? The simple answer: use a route contraint:&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;

&lt;div class="csharpcode"&gt;
  &lt;pre&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;routes.MapRoute(&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   2:  &lt;/span&gt;    &lt;span class="str"&gt;"Default"&lt;/span&gt;, &lt;span class="rem"&gt;// Route name&lt;/span&gt;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   3:  &lt;/span&gt;    &lt;span class="str"&gt;"{controller}/{action}/{id}"&lt;/span&gt;, &lt;span class="rem"&gt;// URL with parameters&lt;/span&gt;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   4:  &lt;/span&gt;    &lt;span class="kwrd"&gt;new&lt;/span&gt; { controller = &lt;span class="str"&gt;"Home"&lt;/span&gt;, action = &lt;span class="str"&gt;"Index"&lt;/span&gt;, id = UrlParameter.Optional }, &lt;span class="rem"&gt;// Parameter defaults&lt;/span&gt;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   5:  &lt;/span&gt;    &lt;span class="kwrd"&gt;new&lt;/span&gt; { controller = &lt;span class="str"&gt;"^(?!Person).*"&lt;/span&gt; }&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   6:  &lt;/span&gt;);&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   7:  &lt;/span&gt; &lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   8:  &lt;/span&gt;routes.Add(&lt;span class="kwrd"&gt;new&lt;/span&gt; ServiceRoute(&lt;span class="str"&gt;"Person"&lt;/span&gt;, &lt;span class="kwrd"&gt;new&lt;/span&gt; WebServiceHostFactory(), &lt;span class="kwrd"&gt;typeof&lt;/span&gt;(PersonService)));&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Notice on line #5 above, we add a route constraint so that it will try to use the MVC route first as long as the first segment (where the “controller” token is positioned) is not the “Person” string which matches where we want our WCF REST service to be. If it is “Person”, then it will fall through to the service route and correctly point to our WCF REST service.&lt;/p&gt;

&lt;p&gt;One other interesting note when using service routes in MVC applications – anytime you’re going beyond the default MVC routes, I highly recommend you unit test your routes. This can be done very easily with the TestHelper that comes with &lt;a href="http://mvccontrib.codeplex.com/" target="_blank"&gt;MvcContrib&lt;/a&gt;. It makes it trivial to unit test routes like this:&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;

&lt;div class="csharpcode"&gt;
  &lt;pre&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;[TestMethod]&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   2:  &lt;/span&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; default_path_should_be_able_to_match_controller()&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   3:  &lt;/span&gt;{&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   4:  &lt;/span&gt;    &lt;span class="str"&gt;"~/"&lt;/span&gt;.Route().ShouldMapTo&amp;lt;HomeController&amp;gt;();            &lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   5:  &lt;/span&gt;}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;The unfortunate caveat here is that you cannot use this when you’re combining service routes. If you do, you’ll get this exception when you initialize your routes at the start of the unit test by invoking the static RegisterRoutes() method: “&lt;strong&gt;System.InvalidOperationException: System.InvalidOperationException: 'ServiceHostingEnvironment.EnsureServiceAvailable' cannot be invoked within the current hosting environment. This API requires that the calling application be hosted in IIS or WAS&lt;/strong&gt;.” Fortunately, we can still use Phil Haack’s &lt;a href="http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx" target="_blank"&gt;Route Debugger&lt;/a&gt;:&lt;/p&gt;

&lt;p&gt; &lt;img alt="wcf route debug" src="http://geekswithblogs.net/images/geekswithblogs_net/michelotti/4145/o_WCFRouteDebug.png" /&gt;&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;With the URL of “/Person/23”, it correctly matches my service route for my WCF service.&lt;/p&gt;

&lt;p&gt;WCF REST and MVC are both great and they should be used *together* when appropriate.&lt;/p&gt; &lt;img src="http://geekswithblogs.net/michelotti/aggbug/141940.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Steve Michelotti</dc:creator>
            <guid>http://geekswithblogs.net/michelotti/archive/2010/09/22/wcf-rest-services-inside-mvc-projects.aspx</guid>
            <pubDate>Thu, 23 Sep 2010 02:55:05 GMT</pubDate>
            <wfw:comment>http://geekswithblogs.net/michelotti/comments/141940.aspx</wfw:comment>
            <comments>http://geekswithblogs.net/michelotti/archive/2010/09/22/wcf-rest-services-inside-mvc-projects.aspx#feedback</comments>
            <slash:comments>7</slash:comments>
            <wfw:commentRss>http://geekswithblogs.net/michelotti/comments/commentRss/141940.aspx</wfw:commentRss>
            <trackback:ping>http://geekswithblogs.net/michelotti/services/trackbacks/141940.aspx</trackback:ping>
        </item>
        <item>
            <title>C# 4 Named Parameters for Overload Resolution</title>
            <link>http://geekswithblogs.net/michelotti/archive/2010/03/16/c-4-named-parameters-for-overload-resolution.aspx</link>
            <description>&lt;p&gt;C# 4 is getting a new feature called named parameters. Although this is a stand-alone feature, it is often used in conjunction with optional parameters. Last week when I was giving a presentation on C# 4, I got a question on a scenario regarding overload resolution that I had not considered before which yielded interesting results. Before I describe the scenario, a little background first.&lt;/p&gt;  &lt;p&gt;Named parameters is a well documented feature that works like this: suppose you have a method defined like this:&lt;/p&gt; &lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;  &lt;div class="csharpcode"&gt;   &lt;pre&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;&lt;span class="kwrd"&gt;void&lt;/span&gt; DoWork(&lt;span class="kwrd"&gt;int&lt;/span&gt; num, &lt;span class="kwrd"&gt;string&lt;/span&gt; message = &lt;span class="str"&gt;"Hello"&lt;/span&gt;)&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   2:  &lt;/span&gt;{&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   3:  &lt;/span&gt;    Console.WriteLine(&lt;span class="str"&gt;"Inside DoWork() - num: {0}, message: {1}"&lt;/span&gt;, num, message);&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   4:  &lt;/span&gt;}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;This enables you to call the method with any of these:&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;

&lt;div class="csharpcode"&gt;
  &lt;pre&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;DoWork(21);&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   2:  &lt;/span&gt;DoWork(num: 21);&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   3:  &lt;/span&gt;DoWork(21, &lt;span class="str"&gt;"abc"&lt;/span&gt;);&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   4:  &lt;/span&gt;DoWork(num: 21, message: &lt;span class="str"&gt;"abc"&lt;/span&gt;);&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;and the corresponding results will be:&lt;/p&gt;

&lt;p&gt;Inside DoWork() - num: 21, message: Hello 
  &lt;br /&gt;Inside DoWork() - num: 21, message: Hello 

  &lt;br /&gt;Inside DoWork() - num: 21, message: abc 

  &lt;br /&gt;Inside DoWork() - num: 21, message: abc&lt;/p&gt;

&lt;p&gt;This is all pretty straight forward and well-documented. What is slightly more interesting is how resolution is handled with method overloads. Suppose we had a second overload for DoWork() that looked like this:&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;

&lt;div class="csharpcode"&gt;
  &lt;pre&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;&lt;span class="kwrd"&gt;void&lt;/span&gt; DoWork(&lt;span class="kwrd"&gt;object&lt;/span&gt; num)&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   2:  &lt;/span&gt;{&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   3:  &lt;/span&gt;    Console.WriteLine(&lt;span class="str"&gt;"Inside second overload: "&lt;/span&gt; + num);&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   4:  &lt;/span&gt;}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;The first rule applied for method overload resolution in this case is that it looks for the most strongly-type match first.  Hence, since the second overload has System.Object as the parameter rather than Int32, this second overload will never be called for any of the 4 method calls above.  But suppose the method overload looked like this:&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;

&lt;div class="csharpcode"&gt;
  &lt;pre&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;&lt;span class="kwrd"&gt;void&lt;/span&gt; DoWork(&lt;span class="kwrd"&gt;int&lt;/span&gt; num)&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   2:  &lt;/span&gt;{&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   3:  &lt;/span&gt;    Console.WriteLine(&lt;span class="str"&gt;"Inside second overload: "&lt;/span&gt; + num);&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   4:  &lt;/span&gt;}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;In this case, both overloads have the first parameter as Int32 so they both fulfill the first rule equally.  In this case the overload with the optional parameters will be ignored if the parameters are not specified. Therefore, the same 4 method calls from above would result in:&lt;/p&gt;

&lt;p&gt;Inside second overload: 21 
  &lt;br /&gt;Inside second overload: 21 

  &lt;br /&gt;Inside DoWork() - num: 21, message: abc 

  &lt;br /&gt;Inside DoWork() - num: 21, message: abc&lt;/p&gt;

&lt;p&gt;Even all this is pretty well documented. However, we can now consider the very interesting scenario I was presented with. The question was what happens if you change the parameter name in one of the overloads.  For example, what happens if you change the parameter *name* for the second overload like this:&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;

&lt;div class="csharpcode"&gt;
  &lt;pre&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;&lt;span class="kwrd"&gt;void&lt;/span&gt; DoWork(&lt;span class="kwrd"&gt;int&lt;/span&gt; num2)&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   2:  &lt;/span&gt;{&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   3:  &lt;/span&gt;    Console.WriteLine(&lt;span class="str"&gt;"Inside second overload: "&lt;/span&gt; + num2);&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   4:  &lt;/span&gt;}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;In this case, the first 2 method calls will yield *&lt;strong&gt;different&lt;/strong&gt;* results:&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;

&lt;div class="csharpcode"&gt;
  &lt;pre&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;DoWork(21);&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   2:  &lt;/span&gt;DoWork(num: 21);&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;results in:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Inside second overload: 21 
    &lt;br /&gt;&lt;font color="#ff0000"&gt;Inside DoWork() - num: 21, message: Hello&lt;/font&gt;&lt;/strong&gt;&lt;/p&gt;
We know the first method call will go to the second overload because of normal method overload resolution rules which ignore the optional parameters.  But for the second call, even though all the same rules apply, the compiler will allow you to specify a named parameter which, in effect, overrides the typical rules and directs the call to the first overload. Keep in mind this would only work if the method overloads had different parameter names for the same types (which in itself is weird). But it is a situation I had not considered before and it is one in which you should be aware of the rules that the C# 4 compiler applies. 

 &lt;img src="http://geekswithblogs.net/michelotti/aggbug/138547.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Steve Michelotti</dc:creator>
            <guid>http://geekswithblogs.net/michelotti/archive/2010/03/16/c-4-named-parameters-for-overload-resolution.aspx</guid>
            <pubDate>Tue, 16 Mar 2010 04:14:02 GMT</pubDate>
            <wfw:comment>http://geekswithblogs.net/michelotti/comments/138547.aspx</wfw:comment>
            <comments>http://geekswithblogs.net/michelotti/archive/2010/03/16/c-4-named-parameters-for-overload-resolution.aspx#feedback</comments>
            <slash:comments>3</slash:comments>
            <wfw:commentRss>http://geekswithblogs.net/michelotti/comments/commentRss/138547.aspx</wfw:commentRss>
            <trackback:ping>http://geekswithblogs.net/michelotti/services/trackbacks/138547.aspx</trackback:ping>
        </item>
        <item>
            <title>.NET 4.0 and Visual Studio 2010 Presentation at Microsoft</title>
            <link>http://geekswithblogs.net/michelotti/archive/2010/01/22/.net-4.0-and-visual-studio-2010-presentation-at-microsoft.aspx</link>
            <description>&lt;p&gt;On February 4th, I will be presenting .NET 4.0 and Visual Studio 2010 at the &lt;a href="http://www.microsoft.com/About/CompanyInformation/usaoffices/midatlantic/mtc_reston.mspx" target="_blank"&gt;Microsoft office in Reston&lt;/a&gt; as part of &lt;a href="http://www.appliedis.com/" target="_blank"&gt;my company’s&lt;/a&gt; continued efforts to provide education on Microsoft technologies. This presentation will cover a wide breadth of technologies that are being launched by Microsoft this year. The presentation is geared towards technical decision makers including Architects, CTO, CIO, Project Managers, IT Managers, and senior development resources. This a totally free Microsoft sponsored event that is intended to provide a solid foundation on the vast landscape of technologies being released and how best they can be leveraged in your organization.  The topics will include:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;.NET Framework 4 enhancements&lt;/li&gt;    &lt;li&gt;Visual Studio 2010&lt;/li&gt;    &lt;li&gt;Parallel Extensions&lt;/li&gt;    &lt;li&gt;C# 4.0 &amp;amp; VB10 language enhancements&lt;/li&gt;    &lt;li&gt;ASP.NET 4&lt;/li&gt;    &lt;li&gt;Microsoft AJAX Library&lt;/li&gt;    &lt;li&gt;MVC 2&lt;/li&gt;    &lt;li&gt;Entity Framework 4&lt;/li&gt;    &lt;li&gt;WCF Data Services&lt;/li&gt;    &lt;li&gt;WCF 4 &amp;amp; REST&lt;/li&gt;    &lt;li&gt;Workflow Foundation 4&lt;/li&gt;    &lt;li&gt;AppFabric&lt;/li&gt;    &lt;li&gt;AppFabric Caching&lt;/li&gt;    &lt;li&gt;Silverlight&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;This event is free and you can &lt;a href="https://www.clicktoattend.com/invitation.aspx?code=144076" target="_blank"&gt;register here&lt;/a&gt;. Hope to see you there.&lt;/p&gt; &lt;img src="http://geekswithblogs.net/michelotti/aggbug/137586.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Steve Michelotti</dc:creator>
            <guid>http://geekswithblogs.net/michelotti/archive/2010/01/22/.net-4.0-and-visual-studio-2010-presentation-at-microsoft.aspx</guid>
            <pubDate>Fri, 22 Jan 2010 18:08:40 GMT</pubDate>
            <wfw:comment>http://geekswithblogs.net/michelotti/comments/137586.aspx</wfw:comment>
            <comments>http://geekswithblogs.net/michelotti/archive/2010/01/22/.net-4.0-and-visual-studio-2010-presentation-at-microsoft.aspx#feedback</comments>
            <wfw:commentRss>http://geekswithblogs.net/michelotti/comments/commentRss/137586.aspx</wfw:commentRss>
            <trackback:ping>http://geekswithblogs.net/michelotti/services/trackbacks/137586.aspx</trackback:ping>
        </item>
        <item>
            <title>Comparing Entity Framework 4 New Stored Procedure Support to LINQ to SQL</title>
            <link>http://geekswithblogs.net/michelotti/archive/2009/12/16/comparing-entity-framework-4-new-stored-procedure-support-to-linq.aspx</link>
            <description>&lt;p&gt;The next version of Entity Framework has many new features, many of which are enabling it to catch up with features previously available in other frameworks like LINQ to SQL.  One of these new features is the updated stored procedure support.  In previous versions of EF, working with stored procedures was quite limited and really only usable with CRUD operations that were mapped to already defined entities.  With EF 4, you can start with your stored procedure and have the &lt;a href="http://blogs.msdn.com/adonet/archive/2009/11/12/automatic-generation-of-stored-procedure-return-types.aspx" target="_blank"&gt;designer automatically generate return types&lt;/a&gt;.  Essentially it will “sense” the shape of the parameters and (if applicable) SELECT statement and generate types that match it or allow you to map it to an already existing type.  This is certainly a great new feature to be adding but, at the same time, these &lt;a href="http://weblogs.asp.net/scottgu/archive/2007/08/16/linq-to-sql-part-6-retrieving-data-using-stored-procedures.aspx" target="_blank"&gt;stored procedure features have been in LINQ to SQL since version 1&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;Although the features are similar between EF 4 and LINQ to SQL, the implementation isn’t exactly the same.  Suppose we have a typical Contact object that looks like this:&lt;/p&gt; &lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;  &lt;div class="csharpcode"&gt;   &lt;pre&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; Contact&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   2:  &lt;/span&gt;{&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   3:  &lt;/span&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; Contact()&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   4:  &lt;/span&gt;    {&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   5:  &lt;/span&gt;        &lt;span class="kwrd"&gt;this&lt;/span&gt;.Addresses = &lt;span class="kwrd"&gt;new&lt;/span&gt; List&amp;lt;Address&amp;gt;();&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   6:  &lt;/span&gt;    }&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   7:  &lt;/span&gt; &lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   8:  &lt;/span&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; ContactId { get; set; }&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   9:  &lt;/span&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; FirstName { get; set; }&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  10:  &lt;/span&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; LastName { get; set; }&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  11:  &lt;/span&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; Email { get; set; }&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  12:  &lt;/span&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; Title { get; set; }&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  13:  &lt;/span&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; ICollection&amp;lt;Address&amp;gt; Addresses { get; set; }&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  14:  &lt;/span&gt;}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;and stored procedure to insert a new contact that takes all of these properties as parameters (with an output parameter for the ContactID since it’s a PK Identity).  If we use the typical edmx approach, we get generated code for this stored procedures that looks like this:&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;

&lt;div class="csharpcode"&gt;
  &lt;pre&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; SaveContact(ObjectParameter contactID, global::System.String firstName, global::System.String lastName, global::System.String company, global::System.String title, global::System.String email)&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   2:  &lt;/span&gt;{&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   3:  &lt;/span&gt;    ObjectParameter firstNameParameter;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   4:  &lt;/span&gt;    &lt;span class="kwrd"&gt;if&lt;/span&gt; (firstName != &lt;span class="kwrd"&gt;null&lt;/span&gt;)&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   5:  &lt;/span&gt;    {&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   6:  &lt;/span&gt;        firstNameParameter = &lt;span class="kwrd"&gt;new&lt;/span&gt; ObjectParameter(&lt;span class="str"&gt;"FirstName"&lt;/span&gt;, firstName);&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   7:  &lt;/span&gt;    }&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   8:  &lt;/span&gt;    &lt;span class="kwrd"&gt;else&lt;/span&gt;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   9:  &lt;/span&gt;    {&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  10:  &lt;/span&gt;        firstNameParameter = &lt;span class="kwrd"&gt;new&lt;/span&gt; ObjectParameter(&lt;span class="str"&gt;"FirstName"&lt;/span&gt;, &lt;span class="kwrd"&gt;typeof&lt;/span&gt;(global::System.String));&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  11:  &lt;/span&gt;    }&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  12:  &lt;/span&gt; &lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  13:  &lt;/span&gt;    ObjectParameter lastNameParameter;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  14:  &lt;/span&gt;    &lt;span class="kwrd"&gt;if&lt;/span&gt; (lastName != &lt;span class="kwrd"&gt;null&lt;/span&gt;)&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  15:  &lt;/span&gt;    {&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  16:  &lt;/span&gt;        lastNameParameter = &lt;span class="kwrd"&gt;new&lt;/span&gt; ObjectParameter(&lt;span class="str"&gt;"LastName"&lt;/span&gt;, lastName);&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  17:  &lt;/span&gt;    }&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  18:  &lt;/span&gt;    &lt;span class="kwrd"&gt;else&lt;/span&gt;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  19:  &lt;/span&gt;    {&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  20:  &lt;/span&gt;        lastNameParameter = &lt;span class="kwrd"&gt;new&lt;/span&gt; ObjectParameter(&lt;span class="str"&gt;"LastName"&lt;/span&gt;, &lt;span class="kwrd"&gt;typeof&lt;/span&gt;(global::System.String));&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  21:  &lt;/span&gt;    }&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  22:  &lt;/span&gt; &lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  23:  &lt;/span&gt;    ObjectParameter companyParameter;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  24:  &lt;/span&gt;    &lt;span class="kwrd"&gt;if&lt;/span&gt; (company != &lt;span class="kwrd"&gt;null&lt;/span&gt;)&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  25:  &lt;/span&gt;    {&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  26:  &lt;/span&gt;        companyParameter = &lt;span class="kwrd"&gt;new&lt;/span&gt; ObjectParameter(&lt;span class="str"&gt;"Company"&lt;/span&gt;, company);&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  27:  &lt;/span&gt;    }&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  28:  &lt;/span&gt;    &lt;span class="kwrd"&gt;else&lt;/span&gt;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  29:  &lt;/span&gt;    {&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  30:  &lt;/span&gt;        companyParameter = &lt;span class="kwrd"&gt;new&lt;/span&gt; ObjectParameter(&lt;span class="str"&gt;"Company"&lt;/span&gt;, &lt;span class="kwrd"&gt;typeof&lt;/span&gt;(global::System.String));&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  31:  &lt;/span&gt;    }&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  32:  &lt;/span&gt; &lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  33:  &lt;/span&gt;    ObjectParameter titleParameter;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  34:  &lt;/span&gt;    &lt;span class="kwrd"&gt;if&lt;/span&gt; (title != &lt;span class="kwrd"&gt;null&lt;/span&gt;)&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  35:  &lt;/span&gt;    {&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  36:  &lt;/span&gt;        titleParameter = &lt;span class="kwrd"&gt;new&lt;/span&gt; ObjectParameter(&lt;span class="str"&gt;"Title"&lt;/span&gt;, title);&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  37:  &lt;/span&gt;    }&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  38:  &lt;/span&gt;    &lt;span class="kwrd"&gt;else&lt;/span&gt;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  39:  &lt;/span&gt;    {&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  40:  &lt;/span&gt;        titleParameter = &lt;span class="kwrd"&gt;new&lt;/span&gt; ObjectParameter(&lt;span class="str"&gt;"Title"&lt;/span&gt;, &lt;span class="kwrd"&gt;typeof&lt;/span&gt;(global::System.String));&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  41:  &lt;/span&gt;    }&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  42:  &lt;/span&gt; &lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  43:  &lt;/span&gt;    ObjectParameter emailParameter;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  44:  &lt;/span&gt;    &lt;span class="kwrd"&gt;if&lt;/span&gt; (email != &lt;span class="kwrd"&gt;null&lt;/span&gt;)&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  45:  &lt;/span&gt;    {&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  46:  &lt;/span&gt;        emailParameter = &lt;span class="kwrd"&gt;new&lt;/span&gt; ObjectParameter(&lt;span class="str"&gt;"Email"&lt;/span&gt;, email);&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  47:  &lt;/span&gt;    }&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  48:  &lt;/span&gt;    &lt;span class="kwrd"&gt;else&lt;/span&gt;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  49:  &lt;/span&gt;    {&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  50:  &lt;/span&gt;        emailParameter = &lt;span class="kwrd"&gt;new&lt;/span&gt; ObjectParameter(&lt;span class="str"&gt;"Email"&lt;/span&gt;, &lt;span class="kwrd"&gt;typeof&lt;/span&gt;(global::System.String));&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  51:  &lt;/span&gt;    }&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  52:  &lt;/span&gt; &lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  53:  &lt;/span&gt;    &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;base&lt;/span&gt;.ExecuteFunction(&lt;span class="str"&gt;"SaveContact"&lt;/span&gt;, contactID, firstNameParameter, lastNameParameter, companyParameter, titleParameter, emailParameter);&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  54:  &lt;/span&gt;}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;It’s good that’s generated code and we don’t have to worry about writing that ourselves but it’s not the prettiest code to look at.  Let’s take a look at the exact same stored procedure call in a LINQ to SQL data context:&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;

&lt;div class="csharpcode"&gt;
  &lt;pre&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;[Function(Name = &lt;span class="str"&gt;"dbo.SaveContact"&lt;/span&gt;)]&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   2:  &lt;/span&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; SaveContact(&lt;span class="kwrd"&gt;ref&lt;/span&gt; Nullable&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt; contactID, &lt;span class="kwrd"&gt;string&lt;/span&gt; firstName, &lt;span class="kwrd"&gt;string&lt;/span&gt; lastName, &lt;span class="kwrd"&gt;string&lt;/span&gt; company, &lt;span class="kwrd"&gt;string&lt;/span&gt; title, &lt;span class="kwrd"&gt;string&lt;/span&gt; email)&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   3:  &lt;/span&gt;{&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   4:  &lt;/span&gt;    IExecuteResult result = &lt;span class="kwrd"&gt;this&lt;/span&gt;.ExecuteMethodCall(&lt;span class="kwrd"&gt;this&lt;/span&gt;, (MethodInfo)MethodInfo.GetCurrentMethod(), contactID, firstName, lastName, company, title, email);&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   5:  &lt;/span&gt;    contactID = (Nullable&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt;)result.GetParameterValue(0);&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   6:  &lt;/span&gt;    &lt;span class="kwrd"&gt;return&lt;/span&gt; (&lt;span class="kwrd"&gt;int&lt;/span&gt;)result.ReturnValue;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   7:  &lt;/span&gt;}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;The first most obvious difference is that’s 54 lines of code for EF 4 and 7 lines of code for LINQ to SQL.  Second, LINQ to SQL allows you to just pass in the primitive types to the built-in ExecuteMethodCall() method whereas EF 4 wants a list of ObjectParameter types for its ExecuteFunction() method.  Third, LINQ to SQL can reflect over the parameters to figure out, by name, which parameters map to which stored procedure parameters (LINQ to SQL also provides the [&lt;a href="http://msdn.microsoft.com/en-us/library/system.data.linq.mapping.parameterattribute.aspx" target="_blank"&gt;Parameter&lt;/a&gt;] attribute if the names or types differ and need to be explicitly mapped). EF, on the other hand, wants the string for the name explicitly set (e.g., “FirstName”, “LastName”, etc.). Also, EF 4 specifies the name of the stored procedure as a parameter to the ExecuteFunction() method, whereas LINQ to SQL specifies it in the [Function] attribute which decorates the method.  Finally, the last interesting difference that I see is in regards to the contact ID property.  That is the PK Identity column that gets assigned from the database on insert.  LINQ to SQL automatically exposes that as a ref parameter (which is an API that makes sense from a C# perspective) and assigns the values after the stored procedure has been invoked via the GetParameterValue() method.  EF 4, on the other hand, exposes that parameter as an actual ObjectParameter (rather than a “ref int”) and all the rest of the parameters as their natural primitives. So the responsibility is on the caller to create the ObjectParameter for the PK property but not for the other ones. This allows the caller to have a reference to the variable so that, in the case of output parameters, it can get at the new value that was just assigned by the database.&lt;/p&gt;

&lt;p&gt;Certainly there are pros and cons of each approach. But I doubt I would be putting myself in the minority to say that I prefer the (much) more succinct API that LINQ to SQL provides. So, while I love the fact that EF 4 is now allowing me to call stored procedures in a similar way to what I had with LINQ to SQL, I’m not absolutely thrilled with the API.&lt;/p&gt;

&lt;p&gt;But, digging a little deeper, how can I add some re-usable methods to be able to give my EF 4 a more succinct API?&lt;/p&gt;

&lt;p&gt;The first thing I want to do is to get an easy way to create all of those ObjectParameters automatically from their primitive types without all the IF statements checking to see if each one is null. If I want to add on to the designer generated code, I can create this method in a partial class. Otherwise, if I’m using the “&lt;a href="http://blogs.msdn.com/adonet/archive/2009/11/12/updated-feature-ctp-walkthrough-code-only-for-entity-framework.aspx" target="_blank"&gt;code only&lt;/a&gt;” approach, I can put this method in my own base ObjectContext class xxxxx:&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;

&lt;div class="csharpcode"&gt;
  &lt;pre&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; SmartObjectContext : ObjectContext&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   2:  &lt;/span&gt;{&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   3:  &lt;/span&gt;    &lt;span class="kwrd"&gt;protected&lt;/span&gt; ObjectParameter[] GetObjectParameters(MethodInfo methodInfo, &lt;span class="kwrd"&gt;params&lt;/span&gt; &lt;span class="kwrd"&gt;object&lt;/span&gt;[] parameters)&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   4:  &lt;/span&gt;    {&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   5:  &lt;/span&gt;        var objectParameters = &lt;span class="kwrd"&gt;new&lt;/span&gt; ObjectParameter[parameters.Length];&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   6:  &lt;/span&gt; &lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   7:  &lt;/span&gt;        var methodParams = methodInfo.GetParameters();&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   8:  &lt;/span&gt;        &lt;span class="kwrd"&gt;for&lt;/span&gt; (&lt;span class="kwrd"&gt;int&lt;/span&gt; i = 0; i &amp;lt; parameters.Length; i++)&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   9:  &lt;/span&gt;        {&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  10:  &lt;/span&gt;            var paramName = methodParams[i].Name;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  11:  &lt;/span&gt;            var paramType = methodParams[i].ParameterType;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  12:  &lt;/span&gt;            var paramValue = parameters[i];&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  13:  &lt;/span&gt;            &lt;span class="kwrd"&gt;if&lt;/span&gt; (paramValue == &lt;span class="kwrd"&gt;null&lt;/span&gt;)&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  14:  &lt;/span&gt;            {&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  15:  &lt;/span&gt;                objectParameters[i] = &lt;span class="kwrd"&gt;new&lt;/span&gt; ObjectParameter(paramName, paramType);&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  16:  &lt;/span&gt;            }&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  17:  &lt;/span&gt;            &lt;span class="kwrd"&gt;else&lt;/span&gt;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  18:  &lt;/span&gt;            {&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  19:  &lt;/span&gt;                objectParameters[i] = &lt;span class="kwrd"&gt;new&lt;/span&gt; ObjectParameter(paramName, parameters[i]);&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  20:  &lt;/span&gt;            }&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  21:  &lt;/span&gt;        }&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  22:  &lt;/span&gt;        &lt;span class="kwrd"&gt;return&lt;/span&gt; objectParameters;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  23:  &lt;/span&gt;    }&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  24:  &lt;/span&gt;}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;This method is clearly not as robust as the LINQ to SQL implementation which optionally takes into account parameter attributes if they exist to further customize the mapping, but it gets the job done.  This now allows my (previously 54 lines) SaveContact() method to now look like this:&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;

&lt;div class="csharpcode"&gt;
  &lt;pre&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; SaveContact(&lt;span class="kwrd"&gt;ref&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; contactID, &lt;span class="kwrd"&gt;string&lt;/span&gt; firstName, &lt;span class="kwrd"&gt;string&lt;/span&gt; lastName, &lt;span class="kwrd"&gt;string&lt;/span&gt; company, &lt;span class="kwrd"&gt;string&lt;/span&gt; title, &lt;span class="kwrd"&gt;string&lt;/span&gt; email)&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   2:  &lt;/span&gt;{&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   3:  &lt;/span&gt;    var objParams = &lt;span class="kwrd"&gt;this&lt;/span&gt;.GetObjectParameters((MethodInfo)MethodInfo.GetCurrentMethod(), contactID, firstName, lastName, company, title, email);&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   4:  &lt;/span&gt;    var result = &lt;span class="kwrd"&gt;this&lt;/span&gt;.ExecuteFunction(&lt;span class="str"&gt;"SaveContact"&lt;/span&gt;, objParams);&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   5:  &lt;/span&gt;    contactID = (&lt;span class="kwrd"&gt;int&lt;/span&gt;)objParams.First(o =&amp;gt; o.Name == &lt;span class="str"&gt;"contactID"&lt;/span&gt;).Value;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   6:  &lt;/span&gt;    &lt;span class="kwrd"&gt;return&lt;/span&gt; result;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   7:  &lt;/span&gt;}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Just by adding this one method to a base class (or current class if you’re using a partial) I was able to reduce my SaveContact() method from 54 lines to 7 lines, and allow the API to be primitives for all parameters including a “ref int” for the PK Identity rather than an ObjectParameter. &lt;/p&gt;

&lt;p&gt;I can also simplify this even further if I’m invoking stored procedures that are not assigning output parameters. For example, suppose you have a simple GetContact stored procedure which takes a single integer contactID as the parameter to the stored procedure. The auto-generated EF 4 code looks like this:&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;

&lt;div class="csharpcode"&gt;
  &lt;pre&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; ObjectResult&amp;lt;Contact&amp;gt; GetContact(Nullable&amp;lt;global::System.Int32&amp;gt; contactID)&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   2:  &lt;/span&gt;{&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   3:  &lt;/span&gt;    ObjectParameter contactIDParameter;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   4:  &lt;/span&gt;    &lt;span class="kwrd"&gt;if&lt;/span&gt; (contactID.HasValue)&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   5:  &lt;/span&gt;    {&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   6:  &lt;/span&gt;        contactIDParameter = &lt;span class="kwrd"&gt;new&lt;/span&gt; ObjectParameter(&lt;span class="str"&gt;"ContactID"&lt;/span&gt;, contactID);&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   7:  &lt;/span&gt;    }&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   8:  &lt;/span&gt;    &lt;span class="kwrd"&gt;else&lt;/span&gt;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   9:  &lt;/span&gt;    {&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  10:  &lt;/span&gt;        contactIDParameter = &lt;span class="kwrd"&gt;new&lt;/span&gt; ObjectParameter(&lt;span class="str"&gt;"ContactID"&lt;/span&gt;, &lt;span class="kwrd"&gt;typeof&lt;/span&gt;(global::System.Int32));&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  11:  &lt;/span&gt;    }&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  12:  &lt;/span&gt; &lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  13:  &lt;/span&gt;    &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;base&lt;/span&gt;.ExecuteFunction&amp;lt;Contact&amp;gt;(&lt;span class="str"&gt;"GetContact"&lt;/span&gt;, contactIDParameter);&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  14:  &lt;/span&gt;}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Notice this is using a different ExecuteFunction() method that is generic and is strongly-typed to the Contact class in this instance.  I can create my own generic ExecuteFunction() method that encapsulates the creation of the ObjectParameter(s) and also put that in my base (or partial) ObjectContext:&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;

&lt;div class="csharpcode"&gt;
  &lt;pre&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; ObjectResult&amp;lt;T&amp;gt; ExecuteFunction&amp;lt;T&amp;gt;(&lt;span class="kwrd"&gt;string&lt;/span&gt; functionName, MethodInfo methodInfo, &lt;span class="kwrd"&gt;params&lt;/span&gt; &lt;span class="kwrd"&gt;object&lt;/span&gt;[] parameters)&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   2:  &lt;/span&gt;{&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   3:  &lt;/span&gt;    var objParams = &lt;span class="kwrd"&gt;this&lt;/span&gt;.GetObjectParameters(methodInfo, parameters);&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   4:  &lt;/span&gt;    &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;base&lt;/span&gt;.ExecuteFunction&amp;lt;T&amp;gt;(functionName, objParams);&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   5:  &lt;/span&gt;}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;What this now allows me to do is to refactor my GetContact() method to now look like this:&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;

&lt;div class="csharpcode"&gt;
  &lt;pre&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; ObjectResult&amp;lt;Contact&amp;gt; GetContact(Nullable&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt; contactID)&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   2:  &lt;/span&gt;{&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   3:  &lt;/span&gt;    &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;this&lt;/span&gt;.ExecuteFunction&amp;lt;Contact&amp;gt;(&lt;span class="str"&gt;"GetContact"&lt;/span&gt;, (MethodInfo)MethodInfo.GetCurrentMethod(), contactID);&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   4:  &lt;/span&gt;}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Essentially this is now down to 1 meaningful line of code.&lt;/p&gt;

&lt;p&gt;A couple of other things to keep in mind – first, the technique of these helper methods can be used regardless of whether you are using EF 4 in “data first”, “model first”, or “code only” scenarios.  Secondly, if you are using edmx files, EF 4 now allows you to customize the generated code that is produced via T4 templates.  So if you don’t like the code that the EF 4 designer is creating for you out of the box, change it!&lt;/p&gt;

&lt;p&gt;One final note on EF 4 stored procedure support: apparently it does *not* support stored procedures that have multiple result sets – this also has been available since the first version of LINQ to SQL via &lt;a href="http://msdn.microsoft.com/en-us/library/system.data.linq.imultipleresults.aspx" target="_blank"&gt;IMultipleResults&lt;/a&gt;. I’m told this functionality can be added to EF with the &lt;a href="http://code.msdn.microsoft.com/EFExtensions" target="_blank"&gt;EF Extensions&lt;/a&gt; library but I have yet to use it myself.&lt;/p&gt;

&lt;p&gt;I’m still in the process of exploring all of the new features being added to EF 4. While some of them are quite interesting (e.g., fluent mappings, etc.), many of the other features being added have already been available in other frameworks like LINQ to SQL.  Definitely good to seem them being added to EF 4 now as well.&lt;/p&gt; &lt;img src="http://geekswithblogs.net/michelotti/aggbug/137019.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Steve Michelotti</dc:creator>
            <guid>http://geekswithblogs.net/michelotti/archive/2009/12/16/comparing-entity-framework-4-new-stored-procedure-support-to-linq.aspx</guid>
            <pubDate>Thu, 17 Dec 2009 04:24:10 GMT</pubDate>
            <wfw:comment>http://geekswithblogs.net/michelotti/comments/137019.aspx</wfw:comment>
            <comments>http://geekswithblogs.net/michelotti/archive/2009/12/16/comparing-entity-framework-4-new-stored-procedure-support-to-linq.aspx#feedback</comments>
            <slash:comments>7</slash:comments>
            <wfw:commentRss>http://geekswithblogs.net/michelotti/comments/commentRss/137019.aspx</wfw:commentRss>
            <trackback:ping>http://geekswithblogs.net/michelotti/services/trackbacks/137019.aspx</trackback:ping>
        </item>
        <item>
            <title>Attaching Modified Entities in EF 4</title>
            <link>http://geekswithblogs.net/michelotti/archive/2009/11/27/attaching-modified-entities-in-ef-4.aspx</link>
            <description>&lt;p&gt;Lately I’ve been working with EF 4.0 and finding that many of the new features are catching up with the features previously available in other framework like LINQ to SQL.  One example of this is the ability to easily attach objects (for example, disconnected objects that come in from another tier).  For example, imagine you had a web service where a consumer submitted an object to get saved – you’d want to instantiate a new context, attach the incoming entity, and save the object.  In previous versions of EF, this was not a trivial thing to do.  However, this was always quite easy to do in LINQ to SQL by doing this:&lt;/p&gt; &lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;  &lt;div class="csharpcode"&gt;   &lt;pre&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt; (var dataContext = &lt;span class="kwrd"&gt;new&lt;/span&gt; MyDataContext())&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   2:  &lt;/span&gt;{&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   3:  &lt;/span&gt;    dataContext.Contacts.Attach(someEntity, &lt;span class="kwrd"&gt;true&lt;/span&gt;);&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   4:  &lt;/span&gt;    dataContext.SubmitChanges();&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   5:  &lt;/span&gt;}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Notice the second Boolean parameters of the &lt;a href="http://msdn.microsoft.com/en-us/library/bb534366.aspx" target="_blank"&gt;Attach&lt;/a&gt;() method – this instructs the context that the entity should treated “as modified” so that an UPDATE command should be issued for that entity when SubmitChanges() gets called (LINQ to SQL also provides an &lt;a href="http://msdn.microsoft.com/en-us/library/bb534401.aspx" target="_blank"&gt;AttachAll&lt;/a&gt;() method for collections).  You can now do the same thing in EF 4 like this (I’m using POCO and Code Only here):&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;

&lt;div class="csharpcode"&gt;
  &lt;pre&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt; (var dataContext = &lt;span class="kwrd"&gt;new&lt;/span&gt; MyDataContext())&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   2:  &lt;/span&gt;{&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   3:  &lt;/span&gt;    dataContext.Contacts.Attach(contact);&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   4:  &lt;/span&gt;    dataContext.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   5:  &lt;/span&gt;    dataContext.SaveChanges();&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   6:  &lt;/span&gt;}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;This is a huge leap forward from previous versions of EF but notice that this actually takes one more line of code than its LINQ to SQL counterpart because an explicit call to the ObjectManager’s ChangeObjectState() method must be called. Although this might appear to be a slight inconvenience, it is possible to write a couple of extension methods to simplify this since the ObjectSet’s all have a reference to the parent Context:&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;

&lt;div class="csharpcode"&gt;
  &lt;pre&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;&lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; ContextExtensions&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   2:  &lt;/span&gt;{&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   3:  &lt;/span&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; AttachAsModified&amp;lt;T&amp;gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; ObjectSet&amp;lt;T&amp;gt; objectSet, T entity) &lt;span class="kwrd"&gt;where&lt;/span&gt; T : &lt;span class="kwrd"&gt;class&lt;/span&gt;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   4:  &lt;/span&gt;    {&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   5:  &lt;/span&gt;        objectSet.Attach(entity);&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   6:  &lt;/span&gt;        objectSet.Context.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   7:  &lt;/span&gt;    }&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   8:  &lt;/span&gt; &lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   9:  &lt;/span&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; AttachAllAsModified&amp;lt;T&amp;gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; ObjectSet&amp;lt;T&amp;gt; objectSet, IEnumerable&amp;lt;T&amp;gt; entities) &lt;span class="kwrd"&gt;where&lt;/span&gt; T : &lt;span class="kwrd"&gt;class&lt;/span&gt;&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  10:  &lt;/span&gt;    {&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  11:  &lt;/span&gt;        &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (var item &lt;span class="kwrd"&gt;in&lt;/span&gt; entities)&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  12:  &lt;/span&gt;        {&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  13:  &lt;/span&gt;            objectSet.Attach(item);&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  14:  &lt;/span&gt;            objectSet.Context.ObjectStateManager.ChangeObjectState(item, EntityState.Modified);&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  15:  &lt;/span&gt;        }&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  16:  &lt;/span&gt;    }&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;  17:  &lt;/span&gt;}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;This allows you to now save like this:&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;

&lt;div class="csharpcode"&gt;
  &lt;pre&gt;&lt;span class="lnum"&gt;   1:  &lt;/span&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt; (var dataContext = &lt;span class="kwrd"&gt;new&lt;/span&gt; MyDataContext())&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   2:  &lt;/span&gt;{&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   3:  &lt;/span&gt;    dataContext.Contacts.AttachAsModified(contact);&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   4:  &lt;/span&gt;    dataContext.SaveChanges();&lt;/pre&gt;

  &lt;pre&gt;&lt;span class="lnum"&gt;   5:  &lt;/span&gt;}&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;This is pretty straight forward and certainly not very complex. However, it is promising that EF is moving in the direction of better enabling these simple scenarios as compared with previous versions.&lt;/p&gt; &lt;img src="http://geekswithblogs.net/michelotti/aggbug/136576.aspx" width="1" height="1" /&gt;</description>
            <dc:creator>Steve Michelotti</dc:creator>
            <guid>http://geekswithblogs.net/michelotti/archive/2009/11/27/attaching-modified-entities-in-ef-4.aspx</guid>
            <pubDate>Sat, 28 Nov 2009 03:12:10 GMT</pubDate>
            <wfw:comment>http://geekswithblogs.net/michelotti/comments/136576.aspx</wfw:comment>
            <comments>http://geekswithblogs.net/michelotti/archive/2009/11/27/attaching-modified-entities-in-ef-4.aspx#feedback</comments>
            <slash:comments>9</slash:comments>
            <wfw:commentRss>http://geekswithblogs.net/michelotti/comments/commentRss/136576.aspx</wfw:commentRss>
            <trackback:ping>http://geekswithblogs.net/michelotti/services/trackbacks/136576.aspx</trackback:ping>
        </item>
    </channel>
</rss>
