<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>David DeWinter &#187; Entity Framework</title>
	<atom:link href="http://blogs.rev-net.com/ddewinter/category/entity-framework/feed/" rel="self" type="application/rss+xml" />
	<link>http://blogs.rev-net.com/ddewinter</link>
	<description>A Developer's Melting Pot: LINQ to SQL, Entity Framework, .NET Security...</description>
	<lastBuildDate>Thu, 08 Apr 2010 17:32:14 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Viewing Generated Proxy Code in the Entity Framework</title>
		<link>http://blogs.rev-net.com/ddewinter/2010/04/08/viewing-generated-proxy-code-in-the-entity-framework/</link>
		<comments>http://blogs.rev-net.com/ddewinter/2010/04/08/viewing-generated-proxy-code-in-the-entity-framework/#comments</comments>
		<pubDate>Thu, 08 Apr 2010 17:16:35 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[.NET4/VS2010]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[POCO]]></category>
		<category><![CDATA[proxies]]></category>
		<category><![CDATA[Reflection.Emit]]></category>

		<guid isPermaLink="false">http://blogs.rev-net.com/ddewinter/?p=304</guid>
		<description><![CDATA[This is one post that&#8217;s been on my to-do list for a while, and since I&#8217;ve seen some questions relating to it in our forums, I thought it appropriate to get it out the door before .NET 4 officially releases.
As you may know, the Entity Framework supports mapping database information to POCO (Plain Old CLR [...]]]></description>
			<content:encoded><![CDATA[<p>This is one post that&#8217;s been on my to-do list for a while, and since I&#8217;ve seen some <a href="http://social.msdn.microsoft.com/Forums/en-US/adonetefx/thread/75a07036-6450-4128-8ad0-c30c9390c5b4">questions</a> relating to it in our forums, I thought it appropriate to get it out the door before .NET 4 officially releases.</p>
<p>As you may know, the Entity Framework supports mapping database information to POCO (Plain Old CLR Objects) classes in .NET 4. Normally, giving you control over your classes would mean we lose out on a few benefits on controlling the classes ourselves, such as lazy loading and change tracking capabilities. However, if your classes meet a few <a href="http://msdn.microsoft.com/en-us/library/dd468057%28VS.100%29.aspx">requirements</a>, then we can dynamically create an assembly at runtime which contains classes that inherit from your POCO types. Today these classes add additional behavior such as lazy loading and change tracking, but in future releases we could potentially augment them to add more features. Typically we refer to these dynamic classes as POCO proxies.</p>
<p>The Entity Framework uses the features in the <a href="http://msdn.microsoft.com/en-us/library/3y322t50.aspx">Reflection.Emit</a> namespace to generate these classes. If you check out Reflector, you can see that the System.Data.Objects.Internal.EntityProxyFactory.GetDynamicModule starts this process by calling <a href="http://msdn.microsoft.com/en-us/library/bs22fky4.aspx">AppDomain.CurrentDomain.DefineDynamicAssembly</a> with the AssemblyBuilderAccess specified in the s_ProxyAssemblyBuilderAccess field. During normal execution, s_ProxyAssemblyBuilderAccess is AssemblyBuilderAccess.Run and will never change, but we added this field as a test hook for other purposes. As a result, you can also save the assembly to disk by setting the s_ProxyAssemblyBuilderAccess field to AssemblyBuilderAccess.RunAndSave with reflection.</p>
<p>You can&#8217;t just save the assembly right away, since we lazily emit new types into the dynamic assembly as they&#8217;re requested. You&#8217;ll need to force the Entity Framework to create proxy types by calling <a href="http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.createproxytypes(VS.100).aspx">ObjectContext.CreateProxyTypes</a> with a list of all POCO types for which you want proxies generated. Then you can save the assembly to disk by calling AssemblyBuilder.Save on the dynamic assembly. If that sounds complicated, don&#8217;t worry. We&#8217;ll walk through some code to make these steps more concrete. Please note that you&#8217;ll need to run in full trust or at least have ReflectionPermission with ReflectionPermissionFlag.MemberAccess to run the code below.</p>
<p>I&#8217;ve attached a solution to this post that shows the code in more detail, but let&#8217;s walk through the major parts. To set up, I&#8217;ve created an Entity Data Model based on the Northwind database, and I&#8217;ve used our <a href="http://blogs.msdn.com/adonet/pages/walkthrough-poco-template-for-the-entity-framework.aspx">POCO templates</a> to create classes that the Entity Framework will create proxy types for. The first step is to set the s_ProxyAssemblyBuilderAccess field via reflection.</p>
<ul>
<p><strong>C#</strong></p>
<div style="font-family: consolas; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: #2b91af">Type</span> entityProxyFactoryType = <span style="color: #2b91af">Type</span>.GetType(</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: #a31515">&quot;System.Data.Objects.Internal.EntityProxyFactory, &quot;</span> + <span style="color: blue">typeof</span>(<span style="color: #2b91af">ObjectContext</span>).Assembly.FullName);</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px"><span style="color: blue">const</span> <span style="color: #2b91af">BindingFlags</span> bindingFlags = <span style="color: #2b91af">BindingFlags</span>.NonPublic | <span style="color: #2b91af">BindingFlags</span>.Static;</p>
<p style="margin: 0px">entityProxyFactoryType.GetField(<span style="color: #a31515">&quot;s_ProxyAssemblyBuilderAccess&quot;</span>, bindingFlags)</p>
<p style="margin: 0px">&#160;&#160;&#160; .SetValue(<span style="color: blue">null</span>, <span style="color: #2b91af">AssemblyBuilderAccess</span>.RunAndSave);</p>
</p></div>
<p><strong>VB</strong></p>
<div style="font-family: consolas; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">Dim</span> entityProxyFactoryType <span style="color: blue">As</span> <span style="color: #2b91af">Type</span> = <span style="color: #2b91af">Type</span>.GetType(</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #a31515">&quot;System.Data.Objects.Internal.EntityProxyFactory, &quot;</span> + <span style="color: blue">GetType</span>(<span style="color: #2b91af">ObjectContext</span>).Assembly.FullName)</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px"><span style="color: blue">Const</span> bindingFlags <span style="color: blue">As</span> <span style="color: #2b91af">BindingFlags</span> = BindingFlags.NonPublic <span style="color: blue">Or</span> BindingFlags.Static</p>
<p style="margin: 0px">entityProxyFactoryType.GetField(<span style="color: #a31515">&quot;s_ProxyAssemblyBuilderAccess&quot;</span>, bindingFlags) _</p>
<p style="margin: 0px">&#160;&#160;&#160; .SetValue(<span style="color: blue">Nothing</span>, <span style="color: #2b91af">AssemblyBuilderAccess</span>.RunAndSave)</p>
</p></div>
</ul>
<p>Next, we need to force the creation of proxy types. Here we&#8217;re using a variable context that represents an ObjectContext we&#8217;re interested in generating proxies for. (Its instantiation is not shown.) Fortunately, the CreateProxyTypes method ignores any types that are not represented by the model, so we can call the method passing all types in the current assembly.</p>
<ul>
<p><strong>C#</strong></p>
<div style="font-family: consolas; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">context.CreateProxyTypes(<span style="color: #2b91af">Assembly</span>.GetExecutingAssembly().GetTypes());</p>
</p></div>
<p><strong>VB</strong></p>
<div style="font-family: consolas; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px">context.CreateProxyTypes(<span style="color: #2b91af">Assembly</span>.GetExecutingAssembly().GetTypes())</p>
</p></div>
</ul>
<p>Finally, we need to access the AssemblyBuilder using a bit of reflection and call its Save method.</p>
<ul>
<p><strong>C#</strong></p>
<div style="font-family: consolas; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">var</span> moduleBuilders = (<span style="color: #2b91af">IDictionary</span>&lt;<span style="color: #2b91af">Assembly</span>, <span style="color: #2b91af">ModuleBuilder</span>&gt;)</p>
<p style="margin: 0px">&#160;&#160;&#160; entityProxyFactoryType.GetField(<span style="color: #a31515">&quot;s_ModuleBuilders&quot;</span>, bindingFlags).GetValue(<span style="color: blue">null</span>);</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px"><span style="color: blue">var</span> pocoProxyModule = moduleBuilders[<span style="color: blue">typeof</span>(<span style="color: #2b91af">NorthwindEntities</span>).Assembly];</p>
<p style="margin: 0px"><span style="color: blue">var</span> pocoProxyAssembly = (<span style="color: #2b91af">AssemblyBuilder</span>)pocoProxyModule.Assembly;</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">pocoProxyAssembly.Save(<span style="color: #a31515">&quot;EntityProxyModule.dll&quot;</span>);</p>
</p></div>
<p><strong>VB</strong></p>
<div style="font-family: consolas; margin-bottom: 10px; background: white; color: black; font-size: 10pt">
<p style="margin: 0px"><span style="color: blue">Dim</span> moduleBuilders = <span style="color: blue">DirectCast</span>(</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; entityProxyFactoryType.GetField(<span style="color: #a31515">&quot;s_ModuleBuilders&quot;</span>, bindingFlags).GetValue(<span style="color: blue">Nothing</span>),&#160; _</p>
<p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">IDictionary</span>(<span style="color: blue">Of</span> <span style="color: #2b91af">Assembly</span>, <span style="color: #2b91af">ModuleBuilder</span>))</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px"><span style="color: blue">Dim</span> pocoProxyModule = moduleBuilders(<span style="color: blue">GetType</span>(<span style="color: #2b91af">NorthwindEntities</span>).Assembly)</p>
<p style="margin: 0px"><span style="color: blue">Dim</span> pocoProxyAssembly = <span style="color: blue">DirectCast</span>(pocoProxyModule.Assembly, <span style="color: #2b91af">AssemblyBuilder</span>)</p>
<p style="margin: 0px">&#160;</p>
<p style="margin: 0px">pocoProxyAssembly.Save(<span style="color: #a31515">&quot;EntityProxyModule.dll&quot;</span>)</p>
</p></div>
</ul>
<p>After the preceding code runs, you&#8217;ll be left with a file named EntityProxyModule.dll in the current directory, which you can easily pop into Reflector to view the code for the proxies. As you can see the names of the generated types are quite long. <img src='http://blogs.rev-net.com/ddewinter/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Since proxies today are tied to the metadata of the ObjectContext by which they were created, we use a hash of the metadata in the proxy&#8217;s type name to correlate the proxy type with that ObjectContext. If we need to use the same CLR type for an ObjectContext with different metadata, we will create a new proxy type.</p>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Proxy assembly in Reflector" border="0" alt="Proxy assembly in Reflector" src="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2010/04/image.png" width="644" height="445" /> </p>
<p>I&#8217;m not going to dive deep into the proxy code, since it resembles code from the default code generation in some ways (e.g. change tracking, relationship management). There is one interesting piece that I&#8217;ll point out and that is how we override navigation properties.</p>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2010/04/image1.png" width="644" height="395" /> </p>
<p>Our overrides are very simple—usually we delegate to the base implementation, but if lazy loading is enabled we will call into a delegate (ef_proxy_interceptor…), which is where we will load the navigation property into memory if it&#8217;s not there already. Of course, in the proxy code there is nothing specific to lazy loading; we just call a delegate that could do any number of things in future.</p>
<p>I encourage you to download the solution and play around with the code. Let me know here or on our <a href="http://social.msdn.microsoft.com/Forums/en-US/adonetefx/threads">forums</a> if you have any additional questions!</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.rev-net.com/ddewinter/2010/04/08/viewing-generated-proxy-code-in-the-entity-framework/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>We&#8217;re Hiring! Test Positions Open on Entity Framework and WCF Data Services (Astoria) Teams</title>
		<link>http://blogs.rev-net.com/ddewinter/2010/01/27/were-hiring-test-positions-open-on-entity-framework-and-wcf-data-services-astoria-teams/</link>
		<comments>http://blogs.rev-net.com/ddewinter/2010/01/27/were-hiring-test-positions-open-on-entity-framework-and-wcf-data-services-astoria-teams/#comments</comments>
		<pubDate>Wed, 27 Jan 2010 16:33:14 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[test]]></category>

		<guid isPermaLink="false">http://blogs.rev-net.com/ddewinter/2010/01/27/were-hiring-test-positions-open-on-entity-framework-and-wcf-data-services-astoria-teams/</guid>
		<description><![CDATA[With work on Visual Studio 2010 winding down, both the Entity Framework and Astoria teams have test engineer positions open. Here are the job postings:

Astoria 
Entity Framework 

Note: If the job descriptions above still say you need C/C++ experience, this is not true. If you don&#8217;t have experience in these areas, don&#8217;t let that discourage [...]]]></description>
			<content:encoded><![CDATA[<p>With work on Visual Studio 2010 winding down, both the Entity Framework and Astoria teams have test engineer positions open. Here are the job postings:</p>
<ul>
<li><a href="https://careers.microsoft.com/JobDetails.aspx?ss=&amp;pg=0&amp;so=&amp;rw=1&amp;jid=11878&amp;jlang=EN">Astoria</a> </li>
<li><a href="https://careers.microsoft.com/JobDetails.aspx?ss=&amp;pg=0&amp;so=&amp;rw=1&amp;jid=11877&amp;jlang=EN">Entity Framework</a> </li>
</ul>
<p><strong><em>Note: If the job descriptions above still say you need C/C++ experience, this is not true. If you don&#8217;t have experience in these areas, don&#8217;t let that discourage you from applying! </em></strong>In fact, I didn&#8217;t have C/C++ experience upon arriving here…</p>
<p>Now, I know what you&#8217;re thinking—&quot;ugh, test, you mean those guys who sit on the other side of the building and click on things all day?&quot; And actually, when I first joined as a tester, I had a bit of the same mentality. That&#8217;s why I wanted to find out for myself what testers actually do. I have worked at Microsoft for a year now as a tester on the Entity Framework team and have learned a lot about the discipline of test, but I know I have only scratched the surface. Also, I should clarify that these positions are opening on the <em>runtime</em> team, so you won&#8217;t be clicking on things that much, if at all. <img src='http://blogs.rev-net.com/ddewinter/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>My background as a .NET developer has really helped me excel as a test engineer. The challenges that we face are very diverse and as a result I think there are many more opportunities for growth in the test discipline than in other disciplines. In a sense, we are developers ourselves; we don&#8217;t ship code (typically), but we must have the ingenuity and creativity to verify the code that does ship meets a high quality bar. Test can be a very demanding discipline, especially for those people who have a background in development.</p>
<p>If you want to know more about my experiences feel free to contact me using the contact form page, and I hope you consider applying if you&#8217;re looking for a challenging job.</p>
<p>P.S. I should note that the Astoria job description is missing an important sales pitch—you get to work with Pablo Castro! Yes, <a href="http://blogs.msdn.com/pablo/">that Pablo</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.rev-net.com/ddewinter/2010/01/27/were-hiring-test-positions-open-on-entity-framework-and-wcf-data-services-astoria-teams/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>POCO Templates for Entity Framework v4 Beta 2 Released</title>
		<link>http://blogs.rev-net.com/ddewinter/2010/01/25/poco-templates-for-entity-framework-v4-beta-2-released/</link>
		<comments>http://blogs.rev-net.com/ddewinter/2010/01/25/poco-templates-for-entity-framework-v4-beta-2-released/#comments</comments>
		<pubDate>Mon, 25 Jan 2010 20:02:31 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[.NET4/VS2010]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[.NET 4]]></category>
		<category><![CDATA[POCO]]></category>

		<guid isPermaLink="false">http://blogs.rev-net.com/ddewinter/2010/01/25/poco-templates-for-entity-framework-v4-beta-2-released/</guid>
		<description><![CDATA[Today we have finally released an update to the POCO Templates that is compatible with Visual Studio 2010 Beta 2. Official announcement on the ADO.NET team blog.
One thing I will highlight is that the templates won&#8217;t be released with the final version of Visual Studio 2010. Instead we will continue to push releases through the [...]]]></description>
			<content:encoded><![CDATA[<p>Today we have finally released an update to the POCO Templates that is compatible with Visual Studio 2010 Beta 2. <a href="http://blogs.msdn.com/adonet/archive/2010/01/25/announcing-the-entity-framework-poco-template-update-for-visual-studio-2010-beta-2.aspx">Official announcement on the ADO.NET team blog.</a></p>
<p>One thing I will highlight is that the templates won&#8217;t be released with the final version of Visual Studio 2010. Instead we will continue to push releases through the <a href="http://visualstudiogallery.msdn.microsoft.com/en-us/">Visual Studio Extension Gallery</a>. This means you can easily download the POCO Templates using Visual Studio&#8217;s Extension Manager (accessed through the Tools menu).</p>
<p><a href="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2010/01/image.png"><img style="border-bottom: 0px; border-left: 0px; display: block; float: none; margin-left: auto; border-top: 0px; margin-right: auto; border-right: 0px" title="Extension Manager menu item" border="0" alt="Extension Manager menu item" src="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2010/01/image_thumb.png" width="613" height="534" /></a> </p>
<p>Once in the Extension Manager, click the Online Gallery tab on the left side of the window and use the search box (top right) to type in &quot;POCO template.&quot; After a few seconds you should see the POCO template extensions appear. There are two extensions, one for C# and one for Visual Basic.</p>
<p><a href="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2010/01/image1.png"><img style="border-bottom: 0px; border-left: 0px; display: block; float: none; margin-left: auto; border-top: 0px; margin-right: auto; border-right: 0px" title="image" border="0" alt="image" src="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2010/01/image_thumb1.png" width="640" height="342" /></a> </p>
<p>After you install the extension, you&#8217;ll have a new item template for C# projects or Visual Basic projects (depending on which you installed) that will allow you to generate POCO entities from an Entity Framework model. For more in depth information on how to use the POCO templates, have a look at the <a href="http://blogs.msdn.com/adonet/pages/walkthrough-poco-template-for-the-entity-framework.aspx">POCO Template Walkthrough</a>.</p>
<p>As always we are interested in your feedback so feel free to request features or report bugs through the <a href="https://connect.microsoft.com/VisualStudio/content/content.aspx?ContentID=12362">Microsoft Connect web site</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.rev-net.com/ddewinter/2010/01/25/poco-templates-for-entity-framework-v4-beta-2-released/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>LINQ Expression Trees and the Specification Pattern</title>
		<link>http://blogs.rev-net.com/ddewinter/2009/05/31/linq-expression-trees-and-the-specification-pattern/</link>
		<comments>http://blogs.rev-net.com/ddewinter/2009/05/31/linq-expression-trees-and-the-specification-pattern/#comments</comments>
		<pubDate>Mon, 01 Jun 2009 00:42:06 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[Design]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[LINQ to SQL]]></category>

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

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

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

		<guid isPermaLink="false">http://blogs.rev-net.com/ddewinter/?p=128</guid>
		<description><![CDATA[Joydip Kanjilal has recently released a book all about the ADO.NET Entity Framework entitled Entity Framework Tutorial. In this book, Kanjilal explains and demonstrates the various features of EF, including how to create an Entity Data Model (EDM), using E-SQL and LINQ to Entities to perform queries, and even an introduction to ADO.NET Data Services [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://aspadvice.com/blogs/joydip/">Joydip Kanjilal</a> has recently released a book all about the ADO.NET Entity Framework entitled <em>Entity Framework Tutorial</em>. In this book, Kanjilal explains and demonstrates the various features of EF, including how to create an Entity Data Model (EDM), using E-SQL and LINQ to Entities to perform queries, and even an introduction to ADO.NET Data Services (Astoria). Packt Publishing has provided me with an excerpt from this book where Kanjilal goes through building an EDM, which you may find below.</p>
<p>You may also be interested in a review that John Kilgo has written about <em>Entity Framework Tutorial</em> located <a href="http://www.dotnetjohn.com/articles.aspx?articleid=274">here</a>. Finally, scripts and code downloads for this book are available <a href="http://www.packtpub.com/support/book/entity-framework-tutorial">here</a>. (You will have to provide your email address.)</p>
<p><span id="more-128"></span></p>
<hr size="1" noshade="noshade"  style="display: block;" />
<div class="header">Entity Framework Tutorial</div>
<table border="0" cellspacing="0" cellpadding="0" width="100%" >
<tbody>
<tr>
<td width="99" valign="top"><a href="http://www.packtpub.com/entity-framework-tutorial/book"><img class="left" title="Entity Framework Tutorial" src="http://images.packtpub.com/images/100x123/1847195229.png" border="0" alt="Entity Framework Tutorial" width="99" height="123" /></a></td>
<td valign="top"  style="padding-left: 10px;">Learn to build a better data access layer with the ADO.NET Entity Framework and ADO.NET Data Services</p>
<ul>
<li>Clear and concise guide to the ADO.NET Entity Framework with plentiful code examples</li>
<li>Create Entity Data Models from your database and use them in your applications</li>
<li>Learn about the Entity Client data provider and create statements in Entity SQL</li>
<li>Learn about ADO.NET Data Services and how they work with the Entity Framework</li>
</ul>
<p><a href="http://www.packtpub.com/entity-framework-tutorial/book">http://www.PacktPub.com/entity-framework-tutorial/book</a></td>
</tr>
</tbody>
</table>
<hr size="1" noshade="noshade" style="display: block;" />
<h2>Creating an Entity Data Model</h2>
<p>You can create the ADO.NET Entity Data Model in one of the two ways:</p>
<ul>
<li>Use the ADO.NET Entity Data Model Designer</li>
<li>Use the command line Entity Data Model Designer called EdmGen.exe</li>
</ul>
<p>We will first take a look at how we can design an Entity Data Model using the ADO.NET Entity Data Model Designer which is a Visual Studio wizard that is enabled after you install ADO.NET Entity Framework and its tools. It provides a graphical interface that you can use to generate an Entity Data Model.</p>
<h2>Creating the Payroll Entity Data Model using the ADO.NET Entity Data Model Designer</h2>
<p>Here are the tables of the &#8216;Payroll&#8217; database that we will use to generate the data model:</p>
<ul>
<li>Employee</li>
<li>Designation</li>
<li>Department</li>
<li>Salary</li>
<li>ProvidentFund</li>
</ul>
<p>To create an entity data model using the ADO.NET Entity Data Model Designer, follow these simple steps:</p>
<ol>
<li>Open Visual Studio.NET and create a solution for a new web application project as seen below and save with a name.
<p style="text-align: center"><img src="http://www.packtpub.com/files/images/ado-net-entity-image1.png" alt="" /></p>
</li>
<li>Switch to the Solution Explorer, right click and click on <strong>Add New Item</strong> as seen in the following screenshot:
<p style="text-align: center"><img src="http://www.packtpub.com/files/images/ado-net-entity-image2.png" alt="" /></p>
</li>
<li>Next, select <strong>ADO.NET Entity Data Model</strong> from the list of the templates displayed as shown in the following screenshot:
<p style="text-align: center"><img src="http://www.packtpub.com/files/images/ado-net-entity-image3.png" alt="" /></p>
</li>
<li>Name the Entity Data Model <strong>PayrollModel</strong> and click on <strong>Add</strong>.</li>
<li>Select <strong>Generate from database</strong> from the Entity Data Model Wizard as shown in the following screenshot:
<p style="text-align: center"><img src="http://www.packtpub.com/files/images/ado-net-entity-image4.png" alt="" /></p>
<p>Note that you can also use the Empty model template to create the Entity Data Model yourself.</p>
<p>If you select the Empty Data Model template and click on next, the following screen appears:</p>
<p style="text-align: center"><img src="http://www.packtpub.com/files/images/ado-net-entity-image5.png" alt="" /></p>
<p>As you can see from the above figure, you can use this template to create the Entity Data Model yourself. You can create the Entity Types and their relationships manually by dragging items from the toolbox. We will not use this template in our discussion here. So, let&#8217;s get to the next step.</li>
<li>Click on <strong>Next</strong> in the Entity Data Model Wizard window shown earlier.</li>
<li>The modal dialog box will now appear and prompts you to choose your connection as shown in the following figure:
<p style="text-align: center"><img src="http://www.packtpub.com/files/images/ado-net-entity-image6.png" alt="" /></p>
</li>
<li>Click on <strong>New Connection</strong> Now you will need to specify the connection properties and parameters as shown in the following figure:
<p style="text-align: center"><img src="http://www.packtpub.com/files/images/ado-net-entity-image7.png" alt="" /></p>
<p style="margin-left: 40px; margin-right: 40px"><em>We will use a dot to specify the database server name. This implies that we will be using the database server of the localhost, which is the current system in use.</em></p>
</li>
<li>After you specify the necessary user name, password, and the server name, you can test your connection using the <strong>Test Connection</strong> button. When you do so, the message <strong>Test connection succeeded</strong> gets displayed in the message box as shown in the previous figure.</li>
<li>When you click on <strong>OK</strong> on the Test connection dialog box, the following screen appears:
<p style="text-align: center"><img src="http://www.packtpub.com/files/images/ado-net-entity-image8.png" alt="" /></p>
<p>Note the Entity Connection String generated automatically. This connection string will be saved in the ConnectionStrings section of your application&#8217;s <em>web.config</em> file. This is how it will look like:</p>
<ol>
<pre>&lt;connectionStrings&gt;
  &lt;add
    name="PayrollEntities"
    connectionString="metadata=res:// *;provider=System.Data.SqlClient;provider connection string=&amp;quot;Data Source=.;Initial Catalog=Payroll;User ID=sa;Password=joydip1@3;MultipleActiveResultSets=True&amp;quot;"
    providerName="System.Data.EntityClient" /&gt;
&lt;/connectionStrings&gt;</pre>
</ol>
</li>
<li>When you click on <strong>Next</strong> in the previous figure, the following screen appears:
<p style="text-align: center"><img src="http://www.packtpub.com/files/images/ado-net-entity-image9.png" alt="" /></p>
</li>
<li>Expand the <strong>Tables</strong> node and specify the database objects that you require in the Entity Data Model to be generated as shown in the following figure:
<p style="text-align: center"><img src="http://www.packtpub.com/files/images/ado-net-entity-image10.png" alt="" /></p>
</li>
<li>Click on <strong>Finish</strong> to generate the Entity Data Model.</li>
</ol>
<p>Here is the output displayed in the Output Window while the Entity Data Model is being generated:</p>
<p style="text-align: center"><img src="http://www.packtpub.com/files/images/ado-net-entity-image11.png" alt="" /></p>
<p>Your Entity Data Model has been generated and saved in a file named <em>PayrollModel.edmx</em>. We are done creating our first Entity Data Model using the ADO.NET Entity Data Model Designer tool.</p>
<p>When you open the Payroll Entity Data Model that we just created in the designer view, it will appear as shown in the following figure:</p>
<p style="text-align: center"><img src="http://www.packtpub.com/files/images/ado-net-entity-image12.png" alt="" /></p>
<p>Note how the Entity Types in the above model are related to one another. These relationships have been generated automatically by the Entity Data Model Designer based on the relationships between the tables of the Payroll database.</p>
<p>In the next section, we will learn how we can create an Entity Data Model using the EdmGen.exe command line tool.</p>
<h2>Creating the Payroll Data Model Using the EdmGen Tool</h2>
<p>We will now take a look at how to create a data model using the Entity Data Model generation tool called EdmGen.</p>
<p>The EdmGen.exe command line tool can be used to do one or more of the following:</p>
<ul>
<li>Generate the <em>.cdsl</em>, <em>.msl</em>, and <em>.ssdl</em> files as part of the Entity Data Model</li>
<li>Generate object classes from a <em>.csdl</em> file</li>
<li>Validate an Entity Data Model</li>
</ul>
<p>The EdmGen.exe command line tool generates the Entity Data Model as a set of three files: <em>.csdl</em>, <em>.msl</em>, and <em>.ssdl</em>. If you have used the ADO.NET Entity Data Model Designer to generate your Entity Data Model, the <em>.edmx</em> file generated will contain the CSDL, MSL, and the SSDL sections. You will have a single <em>.edmx</em> file that bundles all of these sections into it. On the other hand, if you use the EdmGen.exe tool to generate the Entity Data Model, you would find three distinctly separate files with <em>.csdl</em>, <em>.msl</em> or <em>.ssdl </em>extensions.</p>
<p>Here is a list of the major options of the EdmGen.exe command line tool:</p>
<p style="text-align: center">
<div>
<table class="MsoNormalTable" style="border-right: medium none; border-top: medium none; border-left: medium none; border-bottom: medium none; border-collapse: collapse" border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 12.9pt;">
<td style="border: medium none; padding: 0in 5.4pt; width: 191.2pt; height: 12.9pt;" width="255" valign="top">
<p class="Pa50"><strong><span style="font-size: 10pt; color: black;">Option</span></strong><span style="font-size: 10pt; color: black;"></span></p>
</td>
<td style="border: medium none; padding: 0in 5.4pt; width: 191.2pt; height: 12.9pt;" width="255" valign="top">
<p class="Pa50"><strong><span style="font-size: 10pt; color: black;">Description</span></strong><span style="font-size: 10pt; color: black;"></span></p>
</td>
</tr>
<tr style="height: 24.15pt;">
<td style="border: medium none; padding: 0in 5.4pt; width: 191.2pt; height: 24.15pt;" width="255" valign="top">
<p class="Pa50"><span style="font-size: 10pt; color: black;">/help</span></p>
</td>
<td style="border: medium none; padding: 0in 5.4pt; width: 191.2pt; height: 24.15pt;" width="255" valign="top">
<p class="Pa50"><span style="font-size: 10pt; color: black;">Use this option to display help on all the possible options of this tool. The short form is </span><span style="font-size: 10pt; color: black;">/?</span></p>
</td>
</tr>
<tr style="height: 24.15pt;">
<td style="border: medium none; padding: 0in 5.4pt; width: 191.2pt; height: 24.15pt;" width="255" valign="top">
<p class="Pa50"><span style="font-size: 10pt; color: black;">/language:CSharp</span></p>
</td>
<td style="border: medium none; padding: 0in 5.4pt; width: 191.2pt; height: 24.15pt;" width="255" valign="top">
<p class="Pa50"><span style="font-size: 10pt; color: black;">Use this option to generate code using C# language</span></p>
</td>
</tr>
<tr style="height: 24.15pt;">
<td style="border: medium none; padding: 0in 5.4pt; width: 191.2pt; height: 24.15pt;" width="255" valign="top">
<p class="Pa50"><span style="font-size: 10pt; color: black;">/language:VB</span></p>
</td>
<td style="border: medium none; padding: 0in 5.4pt; width: 191.2pt; height: 24.15pt;" width="255" valign="top">
<p class="Pa50"><span style="font-size: 10pt; color: black;">Use this option to generate code using VB language</span></p>
</td>
</tr>
<tr style="height: 24.15pt;">
<td style="border: medium none; padding: 0in 5.4pt; width: 191.2pt; height: 24.15pt;" width="255" valign="top">
<p class="Pa50"><span style="font-size: 10pt; color: black;">/provider:&lt;string&gt;</span></p>
</td>
<td style="border: medium none; padding: 0in 5.4pt; width: 191.2pt; height: 24.15pt;" width="255" valign="top">
<p class="Pa50"><span style="font-size: 10pt; color: black;">Use this option to specify the name of the ADO.NET data provider that you would like to use.</span></p>
</td>
</tr>
<tr style="height: 30.65pt;">
<td style="border: medium none; padding: 0in 5.4pt; width: 191.2pt; height: 30.65pt;" width="255" valign="top">
<p class="Pa50"><span style="font-size: 10pt; color: black;">/connectionstring:</span></p>
<p class="Pa50"><span style="font-size: 10pt; color: black;">&lt;connection string&gt;</span></p>
</td>
<td style="border: medium none; padding: 0in 5.4pt; width: 191.2pt; height: 30.65pt;" width="255" valign="top">
<p class="Pa50"><span style="font-size: 10pt; color: black;">Use this option to specify the connection string to be used to connect to the database</span></p>
</td>
</tr>
<tr style="height: 24.15pt;">
<td style="border: medium none; padding: 0in 5.4pt; width: 191.2pt; height: 24.15pt;" width="255" valign="top">
<p class="Pa50"><span style="font-size: 10pt; color: black;">/namespace:&lt;string&gt;</span></p>
</td>
<td style="border: medium none; padding: 0in 5.4pt; width: 191.2pt; height: 24.15pt;" width="255" valign="top">
<p class="Pa50"><span style="font-size: 10pt; color: black;">Use this option to specify the name of the namespace</span></p>
</td>
</tr>
<tr style="height: 24.15pt;">
<td style="border: medium none; padding: 0in 5.4pt; width: 191.2pt; height: 24.15pt;" width="255" valign="top">
<p class="Pa50"><span style="font-size: 10pt; color: black;">/mode:FullGeneration</span></p>
</td>
<td style="border: medium none; padding: 0in 5.4pt; width: 191.2pt; height: 24.15pt;" width="255" valign="top">
<p class="Pa50"><span style="font-size: 10pt; color: black;">Use this option to generate your CSDL, MSL, and SSDL objects from the database schema</span></p>
</td>
</tr>
<tr style="height: 24.15pt;">
<td style="border: medium none; padding: 0in 5.4pt; width: 191.2pt; height: 24.15pt;" width="255" valign="top">
<p class="Pa50"><span style="font-size: 10pt; color: black;">/mode:EntityClassGeneration</span></p>
</td>
<td style="border: medium none; padding: 0in 5.4pt; width: 191.2pt; height: 24.15pt;" width="255" valign="top">
<p class="Pa50"><span style="font-size: 10pt; color: black;">Use this option to generate your entity classes from a given CSDL file</span></p>
</td>
</tr>
<tr style="height: 24.15pt;">
<td style="border: medium none; padding: 0in 5.4pt; width: 191.2pt; height: 24.15pt;" width="255" valign="top">
<p class="Pa50"><span style="font-size: 10pt; color: black;">/mode:FromSsdlGeneration</span></p>
</td>
<td style="border: medium none; padding: 0in 5.4pt; width: 191.2pt; height: 24.15pt;" width="255" valign="top">
<p class="Pa50"><span style="font-size: 10pt; color: black;">Use this option to generate MSL, CSDL, and Entity Classes from a given SSDL file</span></p>
</td>
</tr>
<tr style="height: 24.15pt;">
<td style="border: medium none; padding: 0in 5.4pt; width: 191.2pt; height: 24.15pt;" width="255" valign="top">
<p class="Pa50"><span style="font-size: 10pt; color: black;">/mode:ValidateArtifacts</span></p>
</td>
<td style="border: medium none; padding: 0in 5.4pt; width: 191.2pt; height: 24.15pt;" width="255" valign="top">
<p class="Pa50"><span style="font-size: 10pt; color: black;">Use this option to validate the CSDL, SSDL, and MSL files</span></p>
</td>
</tr>
<tr style="height: 24.15pt;">
<td style="border: medium none; padding: 0in 5.4pt; width: 191.2pt; height: 24.15pt;" width="255" valign="top">
<p class="Pa50"><span style="font-size: 10pt; color: black;">/mode:ViewGeneration</span></p>
</td>
<td style="border: medium none; padding: 0in 5.4pt; width: 191.2pt; height: 24.15pt;" width="255" valign="top">
<p class="Pa50"><span style="font-size: 10pt; color: black;">Use this option to generate mapping views from the CSDL, SSDL, and MSL files </span></p>
</td>
</tr>
</tbody>
</table>
</div>
<p>Note that you basically need to pass the connection string, specify the mode, and also the project name of the artifact files (<em>.csdl</em>, <em>.msl</em>, and the <em>.ssdl</em> files) to be created. To create the Entity Data Model for our database, open a command window and type in the following:</p>
<pre style="margin-left: 40px">edmgen /mode:fullgeneration /c:"Data Source=.;Initial Catalog=Payroll;User ID=sa;Password=joydip1@3;" /p:Payroll</pre>
<p>This will create a full ADO.NET Entity Data Model for our database. The output is shown in the following figure:</p>
<p style="text-align: center"><img src="http://www.packtpub.com/files/images/ado-net-entity-image13.png" alt="" /></p>
<p>You can now see the list of the files that have been generated:</p>
<p style="text-align: center"><img src="http://www.packtpub.com/files/images/ado-net-entity-image14.png" alt="" /></p>
<p>You can validate the Payroll Entity Data Model that was just created, using the <em>ValidateArtifacts</em> option of the EdmGen command line tool as shown below:</p>
<pre style="margin-left: 40px">EdmGen /mode:ValidateArtifacts /inssdl:Payroll.ssdl /inmsl:Payroll.msl /incsdl:Payroll.csdl</pre>
<p>When you execute the above command, the output will be similar to what is shown in the following figure:</p>
<p style="text-align: center"><img src="http://www.packtpub.com/files/images/ado-net-entity-image15.png" alt="" /></p>
<p>As you can see in the previous figure, there are no warnings or errors displayed. So, our Entity Data Model is perfect.</p>
<p>The section that follows discusses the new Entity Data Source control which was introduced as part of the Visual Studio.NET 2008 SP1 release.</p>
<h2>The ADO.NET Entity Data Source Control</h2>
<p>Data controls are those that can be bound to data from external data sources. These data sources may include databases, XML files, or even flat files. ASP.NET 2.0 introduced some data source controls with a powerful data binding technique so the need for writing lengthy code for binding data to data controls has been eliminated.</p>
<p style="margin-left: 40px; margin-right: 40px"><em>In ASP.NET, the term Data Binding implies binding the controls to data retrieved from a data source and providing a read or write connectivity between these controls and the data that they are bound to.</em></p>
<p>The Entity Data Source control is an example of a data control that is included as part of the Visual Studio 2008 SP1 release and can be used to bind data retrieved from an Entity Data Model to the data bound controls of ASP.NET. If you have installed Visual Studio 2008 SP1, you can see the EntityDataSource control listed in the Data section of your toolbox.</p>
<p>If you cannot locate the EntityDataSource control in the toolbox, follow these steps:</p>
<ol>
<li>Right-click on the <strong>Toolbox</strong> and select the <strong>Choose Items</strong> option as shown in the following figure:
<p style="text-align: center"><img src="http://www.packtpub.com/files/images/ado-net-entity-image16.png" alt="" /></p>
</li>
<li>From the list of the components displayed, scroll down to locate the EntityDataSource in the .NET Framework Components tab. Refer to the following figure:
<p style="text-align: center"><img src="http://www.packtpub.com/files/images/ado-net-entity-image17.png" alt="" /></p>
</li>
<li>Now, check the checkbox next to the EntityDataSource component and click on <strong>OK</strong>.</li>
</ol>
<p>The ADO.NET Entity Data Source control is now added to your toolbox as shown in the following figure:</p>
<p style="text-align: center"><img src="http://www.packtpub.com/files/images/ado-net-entity-image18.png" alt="" /></p>
<p>If the EntityDataSource component is not listed in the list of the componentsdisplayed in the Choose Toolbox Items window, you will have to add it manually. To do this, click on the <strong>Browse</strong> button in the Choose Toolbox Items window, locate the<em>System.Web.Entity.dll</em> in the folder in your system where Microsoft .NET Framework 3.5 has been installed and click on <strong>OK</strong>.</p>
<h2>Implementing Our First Application Using the Entity Framework</h2>
<p>In this section, we will learn how to use the Entity Data Model and the Entity Data Source Control to implement our first program using the Entity Framework. We will use a GridView control to display bound data.</p>
<p>Refer to the solution we created earlier using the Entity Data Model Designer. Now, follow these steps:</p>
<ol>
<li>Drag and drop an Entity Data Source control from the toolbox onto your  <em>Default.aspx</em> web form.</li>
<li>Now, click on the Configure Data Source option to specify the data source. Refer to the following figure:
<p style="text-align: center"><img src="http://www.packtpub.com/files/images/ado-net-entity-image19.png" alt="" /></p>
</li>
<li>Specify the Connection String and DefaultContainerName and then click on  <strong>Next</strong>.</li>
<li>Specify the fields you would want to retrieve from the database table and click on <strong>Finish</strong> when done.</li>
<li>Now, drag and drop a <strong>GridView</strong> control from the toolbox onto the  <em>Default.aspx</em> web form as seen in the following figure:
<p style="text-align: center"><img src="http://www.packtpub.com/files/images/ado-net-entity-image20.png" alt="" /></p>
</li>
<li>Next, use the Choose Data Source option of the GridView control to associate its data source with the Entity Data Source control we created earlier. Refer to the following figure:
<p style="text-align: center"><img src="http://www.packtpub.com/files/images/ado-net-entity-image21.png" alt="" /></p>
</li>
</ol>
<p>Here is how the markup code of the GridView control looks with its templates defined. Note how the DataSourceID of the GridView control has been associated with the Entity Data Source control we created earlier.</p>
<pre style="margin-left: 40px">&lt;asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="EmployeeID" DataSourceID="SqlDataSource1" BorderColor="Black" BorderStyle="Solid" Width="400px"&gt;
  &lt;Columns&gt;
    &lt;asp:BoundField DataField="EmployeeID" HeaderText="Employee ID" ReadOnly="True" SortExpression="EmployeeID" /&gt;
    &lt;asp:BoundField DataField="FirstName" HeaderText="First Name" SortExpression="FirstName" /&gt;
    &lt;asp:BoundField DataField="LastName" HeaderText="Last Name" SortExpression="LastName" /&gt;
    &lt;asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" /&gt;
  &lt;/Columns&gt;
&lt;/asp:GridView&gt;</pre>
<p>We are done! When you execute the application, your output should be similar to what is shown in the following figure:</p>
<p style="text-align: center"><img src="http://www.packtpub.com/files/images/ado-net-entity-image22.png" alt="" /></p>
<hr size="1" noshade="noshade" style="display: block;" />
<div class="header">Entity Framework Tutorial</div>
<table border="0" cellspacing="0" cellpadding="0" width="100%">
<tbody>
<tr>
<td width="99" valign="top"><a href="http://www.packtpub.com/entity-framework-tutorial/book"><img class="left" title="Entity Framework Tutorial" src="http://images.packtpub.com/images/100x123/1847195229.png" border="0" alt="Entity Framework Tutorial" width="99" height="123" /></a></td>
<td valign="top" style="padding-left: 10px;">Learn to build a better data access layer with the ADO.NET Entity Framework and ADO.NET Data Services</p>
<ul>
<li>Clear and concise guide to the ADO.NET Entity Framework with plentiful code examples</li>
<li>Create Entity Data Models from your database and use them in your applications</li>
<li>Learn about the Entity Client data provider and create statements in Entity SQL</li>
<li>Learn about ADO.NET Data Services and how they work with the Entity Framework</li>
</ul>
<p><a href="http://www.packtpub.com/entity-framework-tutorial/book">http://www.PacktPub.com/entity-framework-tutorial/book</a></td>
</tr>
</tbody>
</table>
<hr size="1" noshade="noshade" style="display: block;" />
<h2>About the Author</h2>
<p><strong>Joydip Kanjilal</strong> is a Microsoft MVP in ASP.NET. He has over 12 years of industry experience in IT with more than 6 years in Microsoft .NET and its related technologies. He has authored many articles for some of the most reputable sites like,www.asptoday.com, www.devx.com, www.aspalliance.com, www.aspnetpro.com, www.sql-server-performance.com, www.sswug.com, etc. Several of these articles have been featured at www.asp.net—Microsoft&#8217;s Official Site on ASP.NET. Joydip was also a community credit winner at www.community-credit.com a number of times.</p>
<p>He is currently working as a Senior Consultant in a reputable company in Hyderabad, INDIA. He has years of experience in designing and architecting solutions for various domains. His technical strengths include C, C++, VC++, Java, C#, Microsoft .NET, Ajax, Design Patterns, SQL Server, Operating Systems, and Computer Architecture. Joydip blogs at http://aspadvice.com/blogs/joydip and spends most of his time reading books, blogs, and writing books and articles. His hobbies include watching cricket and soccer and playing chess.</p>
<hr size="1" noshade="noshade"  style="display: block;" />
]]></content:encoded>
			<wfw:commentRss>http://blogs.rev-net.com/ddewinter/2008/12/21/entity-framework-tutorial-excerpt/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Entity Framework Stored Procedure Generation</title>
		<link>http://blogs.rev-net.com/ddewinter/2008/04/26/entity-framework-stored-procedure-generation/</link>
		<comments>http://blogs.rev-net.com/ddewinter/2008/04/26/entity-framework-stored-procedure-generation/#comments</comments>
		<pubDate>Sat, 26 Apr 2008 21:24:13 +0000</pubDate>
		<dc:creator>David DeWinter</dc:creator>
				<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Code Generation]]></category>
		<category><![CDATA[SMO]]></category>
		<category><![CDATA[Sproc]]></category>
		<category><![CDATA[Stored Procedure]]></category>
		<category><![CDATA[T4]]></category>
		<category><![CDATA[Text Template]]></category>

		<guid isPermaLink="false">http://blogs.rev-net.com/ddewinter/index.php/2008/04/26/entity-framework-stored-procedure-generation/</guid>
		<description><![CDATA[At work my team and I are utilizing the ADO.NET Entity Framework as a means to mitigate the object-relational impedance mismatch. Simply put, we&#8217;re utilizing it as an object-relational mapper for our latest project. So far we have been really impressed with the flexibility it provides us, especially surrounding the area of mapping the same [...]]]></description>
			<content:encoded><![CDATA[<p>At work my team and I are utilizing the <a href="http://msdn2.microsoft.com/en-us/library/aa697427(VS.80).aspx">ADO.NET Entity Framework</a> as a means to mitigate the <a href="http://en.wikipedia.org/wiki/Object-Relational_impedance_mismatch">object-relational impedance mismatch</a>. Simply put, we&#8217;re utilizing it as an object-relational mapper for our latest project. So far we have been really impressed with the flexibility it provides us, especially surrounding the area of mapping the same table to multiple entity types and creating inheritance relationships among those entity types. It has proven itself as a much more viable candidate than .netTiers or LINQ to SQL for us.</p>
<p>While I have a lot of praise for the Entity Framework, there are some quirks that take getting used to. For example, you can&#8217;t update properties that are part of a primary key, even though you can update (non-identity) columns that are part of the primary key in SQL Server 2005. Another is the requirement that if an entity will be inserted into the database using a stored procedure, it must also be updated and deleted through a stored procedure. Yet another is that each stored procedure mapped to a particular entity type must have parameters mapped to every association key, regardless of the type of stored procedure (INSERT, UPDATE, or DELETE). For example, consider the following model:</p>
<p><a href="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2008/04/image23.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="378" alt="image" src="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2008/04/image-thumb5.png" width="511" border="0" /></a>&#160;</p>
<p>If I created stored procedures for the Account entity to use in my EF model, they&#8217;d look like this:</p>
<div style="font-size: 8pt; background: white; margin-bottom: 10px; color: black; font-family: courier new">
<p style="margin: 0px; text-align: left"><span style="color: blue">CREATE PROC </span>dbo.Account_Insert</p>
<p style="margin: 0px; text-align: left">(</p>
<p style="margin: 0px; text-align: left">&#160;&#160;&#160; @customerId <span style="color: blue">INT</span></p>
<p style="margin: 0px; text-align: left">)</p>
<p style="margin: 0px; text-align: left"><span style="color: blue">AS</span></p>
<p style="margin: 0px; text-align: left"><span style="color: blue">BEGIN</span></p>
<p style="margin: 0px; text-align: left">&#160;&#160;&#160; <span style="color: blue">INSERT INTO </span>Account (customerId)</p>
<p style="margin: 0px; text-align: left">&#160;&#160;&#160; <span style="color: blue">VALUES </span>(@customerId)</p>
<p style="margin: 0px; text-align: left">&#160;</p>
<p style="margin: 0px; text-align: left">&#160;&#160;&#160; <span style="color: blue">SELECT SCOPE_IDENTITY</span>() <span style="color: blue">as </span>accountId</p>
<p style="margin: 0px; text-align: left"><span style="color: blue">END</span></p>
<p style="margin: 0px; text-align: left">GO</p>
<p style="margin: 0px; text-align: left">&#160;</p>
<p style="margin: 0px; text-align: left"><span style="color: blue">CREATE PROC </span>dbo.Account_Update</p>
<p style="margin: 0px; text-align: left">(</p>
<p style="margin: 0px; text-align: left">&#160;&#160;&#160; @accountId <span style="color: blue">INT</span>,</p>
<p style="margin: 0px; text-align: left">&#160;&#160;&#160; @customerId <span style="color: blue">INT</span></p>
<p style="margin: 0px; text-align: left">)</p>
<p style="margin: 0px; text-align: left"><span style="color: blue">AS</span></p>
<p style="margin: 0px; text-align: left"><span style="color: blue">BEGIN</span></p>
<p style="margin: 0px; text-align: left">&#160;&#160;&#160; <span style="color: blue">UPDATE </span>Account</p>
<p style="margin: 0px; text-align: left">&#160;&#160;&#160; <span style="color: blue">SET </span>customerId = @customerId</p>
<p style="margin: 0px; text-align: left">&#160;&#160;&#160; <span style="color: blue">WHERE </span>accountId = @accountId</p>
<p style="margin: 0px; text-align: left"><span style="color: blue">END</span></p>
<p style="margin: 0px; text-align: left">&#160;</p>
<p style="margin: 0px; text-align: left"><span style="color: blue">CREATE PROC </span>dbo.Account_Delete</p>
<p style="margin: 0px; text-align: left">(</p>
<p style="margin: 0px; text-align: left">&#160;&#160;&#160; @accountId <span style="color: blue">INT</span>,</p>
<p style="margin: 0px; text-align: left">&#160;&#160;&#160; @customerId <span style="color: blue">INT</span></p>
<p style="margin: 0px; text-align: left">)</p>
<p style="margin: 0px; text-align: left"><span style="color: blue">AS</span></p>
<p style="margin: 0px; text-align: left"><span style="color: blue">BEGIN</span></p>
<p style="margin: 0px; text-align: left">&#160;&#160;&#160; <span style="color: blue">DELETE FROM </span>Account</p>
<p style="margin: 0px; text-align: left">&#160;&#160;&#160; <span style="color: blue">WHERE </span>accountId = @accountId</p>
<p style="margin: 0px; text-align: left"><span style="color: blue">END</span></p>
</p></div>
<p>Notice the delete stored procedure&#8212;it must take in both the ID of the Account and the ID of the Customer it is associated with. Based on <a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2984204&amp;SiteID=1">Colin Meek&#8217;s post here</a>, I can understand why this is necessitated by the Entity Framework, but I can&#8217;t dispute the fact that it is different from I&#8217;m used to writing stored procedures.</p>
<p>As we moved towards implementing sprocs for our persistence layer to utilize, we ran into a few problems. At first, we thought we could utilize old templates from CodeSmith and .netTiers to generate sprocs, and our EF model would consume them gracefully. Unfortunately, if we used these templates, we would end up with sprocs like this for the Account table:</p>
<div style="font-size: 8pt; background: white; margin-bottom: 10px; color: black; font-family: courier new">
<p style="margin: 0px; text-align: left"><span style="color: blue">CREATE PROC </span>dbo.Account_Insert</p>
<p style="margin: 0px; text-align: left">(</p>
<p style="margin: 0px; text-align: left">&#160;&#160;&#160; @accountId <span style="color: blue">INT OUTPUT</span>,</p>
<p style="margin: 0px; text-align: left">&#160;&#160;&#160; @customerId <span style="color: blue">INT</span></p>
<p style="margin: 0px; text-align: left">)</p>
<p style="margin: 0px; text-align: left"><span style="color: blue">AS</span></p>
<p style="margin: 0px; text-align: left"><span style="color: blue">BEGIN</span></p>
<p style="margin: 0px; text-align: left">&#160;&#160;&#160; <span style="color: blue">INSERT INTO </span>Account (customerId)</p>
<p style="margin: 0px; text-align: left">&#160;&#160;&#160; <span style="color: blue">VALUES </span>(@customerId)</p>
<p style="margin: 0px; text-align: left">&#160;</p>
<p style="margin: 0px; text-align: left">&#160;&#160;&#160; <span style="color: blue">SET </span>@accountId = <span style="color: blue">SCOPE_IDENTITY</span>()</p>
<p style="margin: 0px; text-align: left"><span style="color: blue">END</span></p>
<p style="margin: 0px; text-align: left">GO</p>
<p style="margin: 0px; text-align: left">&#160;</p>
<p style="margin: 0px; text-align: left"><span style="color: blue">CREATE PROC </span>dbo.Account_Update</p>
<p style="margin: 0px; text-align: left">(</p>
<p style="margin: 0px; text-align: left">&#160;&#160;&#160; @accountId <span style="color: blue">INT</span>,</p>
<p style="margin: 0px; text-align: left">&#160;&#160;&#160; @customerId <span style="color: blue">INT</span></p>
<p style="margin: 0px; text-align: left">)</p>
<p style="margin: 0px; text-align: left"><span style="color: blue">AS</span></p>
<p style="margin: 0px; text-align: left"><span style="color: blue">BEGIN</span></p>
<p style="margin: 0px; text-align: left">&#160;&#160;&#160; <span style="color: blue">UPDATE </span>Account</p>
<p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">SET </span>customerId = @customerId</p>
<p style="margin: 0px; text-align: left">&#160;&#160;&#160; <span style="color: blue">WHERE </span>accountId = @accountId</p>
<p style="margin: 0px; text-align: left"><span style="color: blue">END</span></p>
<p style="margin: 0px; text-align: left">&#160;</p>
<p style="margin: 0px; text-align: left"><span style="color: blue">CREATE PROC </span>dbo.Account_Delete</p>
<p style="margin: 0px; text-align: left">(</p>
<p style="margin: 0px; text-align: left">&#160;&#160;&#160; @accountId <span style="color: blue">INT</span></p>
<p style="margin: 0px; text-align: left">)</p>
<p style="margin: 0px; text-align: left"><span style="color: blue">AS</span></p>
<p style="margin: 0px; text-align: left"><span style="color: blue">BEGIN</span></p>
<p style="margin: 0px; text-align: left">&#160;&#160;&#160; <span style="color: blue">DELETE FROM </span>Account</p>
<p style="margin: 0px; text-align: left">&#160;&#160;&#160; <span style="color: blue">WHERE </span>accountId = @accountId</p>
<p style="margin: 0px; text-align: left"><span style="color: blue">END</span></p>
</p></div>
<p>Notice the slight differences:</p>
<ol>
<li>The INSERT sproc takes in an output parameter for the identity column and then sets the value of that parameter to the ID that was just inserted. The EF version of the sproc does not take in an output parameter; instead it just selects SCOPE_IDENTITY() for the EF to merge back into the Account entity that was inserted. </li>
<li>The DELETE sproc does not take the parameter for the Customer ID, because it is not part of the primary key. </li>
</ol>
<p>This causes some vexation for us because our new business domain houses about forty tables for which we need to write CUD sprocs that fit the Entity Framework&#8217;s rules. We could write them by hand (which would be painful and subject to error), try to modify CodeSmith&#8217;s templates to generate them correctly, or try to generate them using some other way.</p>
<p>From the title of this blog entry, you can probably infer that we didn&#8217;t write them by hand. Furthermore, <a href="http://www.ryanhauert.com">Ryan Hauert</a> and I were toying around with the idea of using <a href="http://dotnet.org.za/hiltong/archive/2008/02/18/t4-template-items.aspx">T4</a>&#160;<a href="http://www.olegsych.com/2007/12/text-template-transformation-toolkit/">Templates</a> to generate the SQL we needed. In all honesty, we didn&#8217;t even consider modifying the CodeSmith templates; I don&#8217;t think this was a bad choice, as T4 templates can benefit people who don&#8217;t want to purchase CodeSmith, but it may&#8217;ve been easier for our particular situation. But I digress&#8230;</p>
<p>The T4 template we created is designed to be a general purpose way to generate CUD procedures for an Entity Framework model. In case you didn&#8217;t read the links I provided on the templates, they are code-generation files which are intrinsically recognized by Visual Studio 2008. (They required the VS SDK in VS2005.) They have a .tt extension, and Visual Studio will nested generated code files underneath them in the Solution Explorer, similar to how designer files are nested under Entity Framework and LINQ to SQL models.</p>
<p><a href="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2008/04/image24.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="659" alt="image" src="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2008/04/image-thumb6.png" width="814" border="0" /></a></p>
<p>It&#8217;s a very simple process to use the T4 template:</p>
<ol>
<li>Add the file into your project. (The file is linked at the end of the blog entry.) </li>
<li>Simply save the template file and CUD sprocs will be generated for <strong>every</strong> EDMX file in the current directory. </li>
</ol>
<p>If you want to change what directory the template looks in or what files it generates sprocs for, look at the configuration parameters on lines 24 and 25 in the picture above. You can specify the directory explicitly by initializing the directoryName variable to anything other than the empty string or null. Furthermore, if you want to match a specific EDMX file only, you can use a regular expression to filter out unwanted files. I could use it like this:</p>
<div style="font-size: 8pt; background: white; margin-bottom: 10px; color: black; font-family: courier new">
<p style="margin: 0px; text-align: left"><span style="color: #2b91af">Regex</span> edmxFileFilter = <span style="color: blue">new</span> <span style="color: #2b91af">Regex</span>(<span style="color: #a31515">@&quot;Entities\.edmx&quot;</span>);</p>
</p></div>
<p>Then only the Entities.edmx file would be processed.</p>
<p>The template not only generates EF-compliant sprocs, but it also considers only the tables that are in the SSDL of the model file. Unfortunately, the template must query the database (SQL Server 2005 only!) in order to make all the decisions necessary to create the output file. However, this is usually quite fast on generations other than the first one.</p>
<p>As you can see from the picture above, the template requires a few different assemblies to be installed. Most of them shouldn&#8217;t be a problem when generating EF sprocs, because it strongly suggests that you have the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=333325FD-AE52-4E35-B531-508D977D32A6&amp;displaylang=en">.NET Framework 3.5</a> installed. Something you may not have are the SQL Server Server Management Objects (SMO), which offer an abstraction layer over the metadata of a SQL Server instance (e.g. databases, tables, columns, keys, indexes, data types), and keep the template cleaner than if we had to make ad hoc queries directly. The SMO installation is available on <a href="http://www.microsoft.com/downloads/details.aspx?familyid=DF0BA5AA-B4BD-4705-AA0A-B477BA72A9CB&amp;displaylang=en">this page</a>, where its installer is called &quot;SQLServer2005_XMO.msi.&quot; There are other installers for 64-bit and Itanium 64-bit.</p>
<p>Once that is installed the template is very simple to run and gives us output like this:</p>
<p><a href="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2008/04/image25.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="689" alt="image" src="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2008/04/image-thumb7.png" width="792" border="0" /></a></p>
<p>Now we can take this script and run it against SQL Server and then import the sprocs into our Entity Framework model. Finally we can map the stored procedures to the entity types they encapsulate and voil&#224;! We&#8217;re done.</p>
<p>There are a few limitations with the template the moment, but it will account for most cases:</p>
<ol>
<li>No stored procedures are generated for tables that do not have primary keys (in the database, not in the EF model). There is no way we can infer what you meant for the key to be for the update and delete sprocs; while we could generate insert procedures, it wouldn&#8217;t help the end user because the EF requires that an entity type be mapped to all three, or none at all. </li>
<li>The template is available only in C# at the moment. </li>
<li>It has not been tested in all scenarios, so any feedback you have would be great. <img src='http://blogs.rev-net.com/ddewinter/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  </li>
<li><strong>It does not account for entity inheritance.</strong> </li>
</ol>
<p><a style="font-size: 200%" href="http://blogs.rev-net.com/ddewinter/wp-content/uploads/2008/04/EntitySprocsb3.tt">Download T4 Template</a></p>
<p>Special thanks to Bob Pace for giving Ryan and me the idea and providing helpful resources on T4.</p>
<p>Also, if you want to get started writing your own T4 templates, check out <a href="http://dotnet.org.za/hiltong/">Hilton Giesenow</a>&#8217;s excellent video <a href="http://msdn2.microsoft.com/en-gb/vstudio/cc308634.aspx">here</a>.</p>
<p><strong>May 22, 2008 &#8211; Updates:</strong></p>
<p>Ryan and I ran into an issue recently where we were accidentally comparing all of the parameters against values in database rows for the delete stored procedures. This was a mistake, because we really only need to check for equality on the primary key columns. The new template has been uploaded.</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.rev-net.com/ddewinter/2008/04/26/entity-framework-stored-procedure-generation/feed/</wfw:commentRss>
		<slash:comments>38</slash:comments>
		</item>
	</channel>
</rss>
