<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0"><channel><title>Moses' Blog</title><link>http://mosesofegypt.net/</link><description>Living {.net} lifestyle</description><language>en-GB</language><managingEditor>noemail@noemail.org (Muhammad Mosa)</managingEditor><generator>BlogEngine.NET 1.5.0.7</generator><blogChannel:blogRoll xmlns:blogChannel="http://backend.userland.com/blogChannelModule">http://mosesofegypt.net/opml.axd</blogChannel:blogRoll><blogChannel:blink xmlns:blogChannel="http://backend.userland.com/blogChannelModule">http://mosesofegypt.net/syndication.axd</blogChannel:blink><dc:title xmlns:dc="http://purl.org/dc/elements/1.1/">Moses' Blog</dc:title><geo:lat xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">0.000000</geo:lat><geo:long xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">0.000000</geo:long><creativeCommons:license>http://creativecommons.org/licenses/by-sa/3.0/</creativeCommons:license><image><link>http://creativecommons.org/licenses/by-sa/3.0/</link><url>http://creativecommons.org/images/public/somerights20.gif</url><title>Some Rights Reserved</title></image><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" href="http://feeds.feedburner.com/MosesOfEgyptBlog" type="application/rss+xml" /><feedburner:emailServiceId>MosesOfEgyptBlog</feedburner:emailServiceId><feedburner:feedburnerHostname>http://feedburner.google.com</feedburner:feedburnerHostname><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com" /><item><title>KiGG Design And Architecture – Part 1 The high level design</title><link>http://feedproxy.google.com/~r/MosesOfEgyptBlog/~3/7Y_xZBvbUXo/post.aspx</link><category>MVC</category><category>Software Design</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:creator><pubDate>Sat, 14 Nov 2009 14:13:22 PST</pubDate><guid isPermaLink="false">http://mosesofegypt.net/post.aspx?id=73b45693-d038-4e56-9311-f5c7b53719c5</guid><description>&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/x8kNqzbpW0cHQho7mKonW20Obcg/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/x8kNqzbpW0cHQho7mKonW20Obcg/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/x8kNqzbpW0cHQho7mKonW20Obcg/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/x8kNqzbpW0cHQho7mKonW20Obcg/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;h2&gt;Introduction&lt;/h2&gt;  &lt;p&gt;In this multi part series I am going to explore &lt;a href="http://kigg.codeplex.com/" target="_blank"&gt;KiGG&lt;/a&gt; design and architecture as well as projects structures.&lt;/p&gt;  &lt;p&gt;At the beginning I would like to give a brief about &lt;a href="http://kigg.codeplex.com/" target="_blank"&gt;KiGG&lt;/a&gt; History.&lt;/p&gt;  &lt;h2&gt;About KiGG&lt;/h2&gt;  &lt;p&gt;&lt;a href="http://kigg.codeplex.com/" target="_blank"&gt;KiGG&lt;/a&gt; is similar to &lt;a href="http://www.dotnetkicks.com/" target="_blank"&gt;DotNetKicks&lt;/a&gt;, &lt;a href="http://digg.com/" target="_blank"&gt;Digg&lt;/a&gt; and &lt;a href="http://www.dzone.com/" target="_blank"&gt;DZone&lt;/a&gt;. However it much closed to &lt;a href="http://www.dotnetkicks.com/" target="_blank"&gt;DotNetKicks&lt;/a&gt; and way smaller than &lt;a href="http://www.dzone.com/" target="_blank"&gt;DZone&lt;/a&gt;. KiGG was founded by &lt;a href="http://weblogs.asp.net/rashid/" target="_blank"&gt;Kazi Manzur Rashid&lt;/a&gt; and first introduced in his article on &lt;a href="http://dotnetslackers.com" target="_blank"&gt;DotNetSlackers.com&lt;/a&gt;: &lt;a href="http://dotnetslackers.com/articles/aspnet/KiggBuildingADiggCloneWithASPNETMVC1.aspx" target="_blank"&gt;Kigg - Building a Digg Clone with ASP.NET MVC&lt;/a&gt;, that was on Feb 2008. It was built with First ASP.NET MVC preview.&lt;/p&gt;  &lt;p&gt;In early this year 2009 on January, &lt;a href="http://weblogs.asp.net/rashid/" target="_blank"&gt;Rashid&lt;/a&gt; was almost done with KiGG, however ASP.NET MVC 1.0 was not released yet. At this time &lt;a href="http://weblogs.asp.net/rashid/" target="_blank"&gt;Rashid&lt;/a&gt; &lt;a href="http://weblogs.asp.net/rashid/archive/2009/01/20/introducing-dotnetshoutout-com.aspx" target="_blank"&gt;announced DotNetShoutout.com&lt;/a&gt; as first live application based on &lt;a href="http://kigg.codeplex.com/" target="_blank"&gt;KiGG&lt;/a&gt;. On March 2009 Rashid released version 2.2 of &lt;a href="http://kigg.codeplex.com/" target="_blank"&gt;KiGG&lt;/a&gt; after the release of ASP.NET MVC 1.0.&lt;/p&gt;  &lt;p&gt;I joined the team on April and start working with Entity Framework implementation for &lt;a href="http://kigg.codeplex.com/" target="_blank"&gt;KiGG&lt;/a&gt; as well as supporting the project.&lt;/p&gt;  &lt;p&gt;Thank you &lt;a href="http://weblogs.asp.net/rashid/" target="_blank"&gt;Rashid&lt;/a&gt; for giving me this opportunity.&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;h2&gt;High Level Architecture&lt;/h2&gt;  &lt;p&gt;The below picture shows high level architecture of &lt;a href="http://kigg.codeplex.com/" target="_blank"&gt;KiGG&lt;/a&gt; as I view it and tried to simplify it.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://mosesofegypt.net/image.axd?picture=KiGGHighLevelArch.png"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="KiGGHighLevelArch" border="0" alt="KiGGHighLevelArch" src="http://mosesofegypt.net/image.axd?picture=KiGGHighLevelArch_thumb.png" width="400" height="257" /&gt;&lt;/a&gt;     &lt;br /&gt;&lt;em&gt;Figure 01- KiGG high level design&lt;/em&gt;&lt;/p&gt;  &lt;p&gt;As the diagram describes, KiGG consists of 6 main artifacts, &lt;em&gt;Infrastructure&lt;/em&gt;, &lt;em&gt;Domain Model&lt;/em&gt;, &lt;em&gt;Repositories&lt;/em&gt;, &lt;em&gt;Services&lt;/em&gt;, &lt;em&gt;Presentation&lt;/em&gt; and &lt;em&gt;IoC/DI&lt;/em&gt;.&lt;/p&gt;  &lt;p&gt;This is not the best design, and the design contains many sections in which we can tweak and tackle to provide better improved design. I am going to give a brief about each of these major artifacts.&lt;/p&gt;  &lt;h2&gt;1. Infrastructure&lt;/h2&gt;  &lt;p&gt;Contains definition and contracts for KiGG infrastructure. This includes logging, caching, event aggregator, background tasks, bootstrapper, etc… IoC/DI is also considered part of the infrastructure.&lt;/p&gt;  &lt;h2&gt;2. Domain Model&lt;/h2&gt;  &lt;p&gt;Domain models are KiGG entities such as participant users, stories, comments etc. Domain models are shared across and used by all artifacts as shown in the diagram. But models itself do not use any of these artifacts.&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;h2&gt;3. Repositories&lt;/h2&gt;  &lt;p&gt;Core data access definition. KiGG came with 2 repository implementation, first one based on LINQ to SQL, and the second is Entity Framework which support multiple database engine. Currently works KiGG works with SQL Server and MySQL. Repositories interacts with infrastructure to gain benefits of logging, caching and IoC.&lt;/p&gt;  &lt;h2&gt;4. Services&lt;/h2&gt;  &lt;p&gt;Contains different types of services such as story weight calculator, spam calculator, firing system events such as story published or submitted events etc… Services interacts with repositories and infrastructure. However it is not a rule that each repository has a service in services component.Services might also contain few background tasks.&lt;/p&gt;  &lt;h2&gt;5. Presentation&lt;/h2&gt;  &lt;p&gt;Presentation is implemented using ASP.NET MVC 1.0 with jQuery as scripting and AJAX framework. Presentation access infrastructure, services and repositories through IoC. This layer also has its own presentation domain models (View Data). Http modules and handlers also implemented in this component,&lt;/p&gt;  &lt;h2&gt;Conclusion&lt;/h2&gt;  &lt;p&gt;This is KiGG very high level design that shows core artifacts and high level communication between them. I can call bird’s eye view on KiGG from sky.&lt;/p&gt;  &lt;p&gt;This is not the best design as I mentioned earlier, however we might refine it later when we move to .Net 4.0.&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=7Y_xZBvbUXo:9YAFdKpaUps:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=7Y_xZBvbUXo:9YAFdKpaUps:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?i=7Y_xZBvbUXo:9YAFdKpaUps:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=7Y_xZBvbUXo:9YAFdKpaUps:7Q72WNTAKBA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=7Q72WNTAKBA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=7Y_xZBvbUXo:9YAFdKpaUps:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=7Y_xZBvbUXo:9YAFdKpaUps:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?i=7Y_xZBvbUXo:9YAFdKpaUps:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/MosesOfEgyptBlog/~4/7Y_xZBvbUXo" height="1" width="1"/&gt;</description><dc:publisher xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:publisher><pingback:server xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/pingback.axd</pingback:server><pingback:target xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/post.aspx?id=73b45693-d038-4e56-9311-f5c7b53719c5</pingback:target><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">1</slash:comments><trackback:ping xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">http://mosesofegypt.net/trackback.axd?id=73b45693-d038-4e56-9311-f5c7b53719c5</trackback:ping><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/post/kigg-design-and-architecture-part1-high-level-design.aspx#comment</wfw:comment><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/syndication.axd?post=73b45693-d038-4e56-9311-f5c7b53719c5</wfw:commentRss><feedburner:origLink>http://mosesofegypt.net/post.aspx?id=73b45693-d038-4e56-9311-f5c7b53719c5</feedburner:origLink></item><item><title>Entity Framework 4.0 Beta 1 Sneak Peak Session at DotNetWork User Group in Cairo, Egypt</title><link>http://feedproxy.google.com/~r/MosesOfEgyptBlog/~3/LTMP6fRm7VQ/post.aspx</link><category>Entity Framework</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:creator><pubDate>Mon, 05 Oct 2009 07:05:31 PDT</pubDate><guid isPermaLink="false">http://mosesofegypt.net/post.aspx?id=4ae9bbfb-4a54-40e5-9a6d-ee8f056607d1</guid><description>&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/W7McfRKG-tY6aN3qsgC9FWrYAhw/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/W7McfRKG-tY6aN3qsgC9FWrYAhw/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/W7McfRKG-tY6aN3qsgC9FWrYAhw/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/W7McfRKG-tY6aN3qsgC9FWrYAhw/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;h3&gt;Introduction&lt;/h3&gt;  &lt;p&gt;Again I was honored to present a talk on first Egyptian .Net user group “&lt;a href="http://dotnetwork.org/" target="_blank"&gt;DotNetWork&lt;/a&gt;”. &lt;a href="http://mosesofegypt.net/post/Introducing-Entity-Framework-v1-in-DotNetWork-User-Group-in-Cairo-Egypt.aspx" target="_blank"&gt;My previous session&lt;/a&gt; -the first- was a joint session with &lt;a href="http://maximumcs.wordpress.com/" target="_blank"&gt;Bishoy Ghaly&lt;/a&gt; about Entity Framework v1 in .Net 3.5 SP1. This session was about Entity Framework 4.0.&lt;/p&gt;  &lt;p&gt;After we introduced Entity Framework to Egyptian community, I decided to give them a sneak peak at the new version of it. Comparing between both versions, showing the evolution and the massive enhancement made on the new version. The session covered the early &lt;a href="http://mosesofegypt.net/post/Microsoft-ADONET-Entity-Framework-Feature-CTP-1-Post-Beta-1.aspx" target="_blank"&gt;CTP 1 of Entity Framework 4.0 Beta 1&lt;/a&gt; that is released last June.&lt;/p&gt;  &lt;p&gt;Presentation is available to &lt;a href="http://mosesofegypt.net/file.axd?file=EF4PreviewDotNetWorkSession.zip" target="_blank"&gt;download here&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;h3&gt;Audiences&lt;/h3&gt;  &lt;p&gt;The main targeted audiences of this talk those who already had their hands on Entity Framework before. Those who experienced current version of Entity Framework on a way or another. And I would give my session level 200. So attending the &lt;a href="http://mosesofegypt.net/post/Introducing-Entity-Framework-v1-in-DotNetWork-User-Group-in-Cairo-Egypt.aspx" target="_blank"&gt;first session&lt;/a&gt; in which we introduced Entity Framework was the least requirement for those who don’t know Entity Framework. Plus give it some hands on code to see what Entity Framework looks like.&lt;/p&gt;  &lt;p&gt;The real audiences were totally something different. Few of them attended the first session. And I can sense that they didn’t really practice Entity Framework enough to know it well.&lt;/p&gt;  &lt;p&gt;Part of the audiences were already didn’t know what’s ORM –probably students-! Some others where having their very first time to see what is Entity Framework and what it can do.&lt;/p&gt;  &lt;p&gt;To be honest, to satisfy this kind of audiences is very hard! And I really hope that I was able to deliver as much as I can about what is Entity Framework, what it can do and comparing between current version and upcoming one.&lt;/p&gt;  &lt;h3&gt;Session Agenda&lt;/h3&gt;  &lt;p&gt;My agenda for the session was in the following sequence:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;What’s new in Entity Framework 4.0 at glance &lt;/li&gt;    &lt;li&gt;Designer enhancements &lt;/li&gt;    &lt;li&gt;Deferred loading Vs Explicit loading &lt;/li&gt;    &lt;li&gt;&lt;a href="http://blogs.msdn.com/adonet/archive/2009/06/22/feature-ctp-walkthrough-poco-templates-for-entity-framework.aspx" target="_blank"&gt;Persistence Ignorance support {POCO}&lt;/a&gt; (CTP 1) &lt;/li&gt;    &lt;li&gt;Code Generation Customizing with T4 templates &lt;/li&gt;    &lt;li&gt;&lt;a href="http://blogs.msdn.com/adonet/archive/2009/06/22/feature-ctp-walkthrough-code-only-for-entity-framework.aspx" target="_blank"&gt;Code Only support in EF 4.0&lt;/a&gt; (CTP 1) &lt;/li&gt;    &lt;li&gt;&lt;a href="http://blogs.msdn.com/adonet/archive/2009/06/22/feature-ctp-walkthrough-self-tracking-entities-for-entity-framework.aspx" target="_blank"&gt;Self tracking entities support in EF 4.0&lt;/a&gt; (CTP 1) &lt;/li&gt;    &lt;li&gt;Model functions in EF 4.0 (Optional and trimmed for the time) &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;On the following I’m going to give a summary about my talk on each topic on the above agenda.&lt;/p&gt;  &lt;h4&gt;What’s new in Entity Framework 4.0 at glance&lt;/h4&gt;  &lt;p&gt;In this topic a comparison between current version of Entity Framework and vNext of Entity Framework was important. I talked about designer enhancements in general such as Pluralization &amp;amp; Singularization, support complex types and support for stored procedure mapping through the designer. I highlighted to the audiences how this was a problem in current version of Entity Framework and talked about where exactly the issues resides and how Entity Framework 4 Designer in VS.NET 2010 is going to solve these issues making development with Entity Framework more productive.&lt;/p&gt;  &lt;p&gt;I also gave a hint about new APIs enhancements and additions which ease the development and testability of Entity Framework.&lt;/p&gt;  &lt;p&gt;Other general overview and highlights about T4 templates and code generation customization, support of POCO, model first, code only etc…&lt;/p&gt;  &lt;p&gt;This part of the session was just glance overview about some of the new stuff introduced in Entity Framework.&lt;/p&gt;  &lt;h4&gt;Designer Enhancements&lt;/h4&gt;  &lt;p&gt;Demos starts from here, people love to see things in action. So I demonstrated practically how &lt;a href="http://www.thedatafarm.com/Blog/2009/05/21/TheMuchImprovedEDMWizardPluralizationInVS2010.aspx" target="_blank"&gt;Pluralization &amp;amp; Singularization&lt;/a&gt; works. And of course showed them how I am happy that I got this in EF4 as it wasn’t presented in current version.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://thedatafarm.com/blog/data-access/complex-types-in-the-edm-designer-in-ef4-and-a-look-at-updating-complex-types-in-code/" target="_blank"&gt;Then the magic of refactoring to complex type&lt;/a&gt;! Sadly I was able to show them the magic, but couldn’t show them why this is magic by showing them practically that it will require us to modify the XML to add the complex type and do the mapping to get the job done on current version of Entity Framework.&lt;/p&gt;  &lt;p&gt;Next demo was about &lt;a href="http://thedatafarm.com/blog/data-access/a-big-step-for-stored-procedures-in-ef4/" target="_blank"&gt;mapping stored procedures to complex types&lt;/a&gt;! Another big improvement in Entity Framework.&lt;/p&gt;  &lt;p&gt;Also showed them that updating model from database won’t erase manual modifications to entities! this is also was one of the limitation in current version which I highlighted.&lt;/p&gt;  &lt;p&gt;There was another demo in this topic that I skipped for time. It was about Improvements in mapping insert,update &amp;amp; delete operations to stored procedure through Entity Framework designer. I just highlighted the difficulties in current version and told them that this is no more limitation and it is easy and straight forward to be done.&lt;/p&gt;  &lt;h4&gt;Deferred Loading Vs Explicit loading&lt;/h4&gt;  &lt;p&gt;One important topic raised since Entity Framework released. On of the demanded features was the support of deferred loading.&lt;/p&gt;  &lt;p&gt;We didn’t go through eager loading, because it was one of the topics introduced on first session about EF, to save time I didn’t present it here.&lt;/p&gt;  &lt;p&gt;I explained how explicit loading works in Entity Framework. Also introduced new explicit loading API in ObjectContext class which is &lt;em&gt;LoadProperty&lt;/em&gt; method.&lt;/p&gt;  &lt;p&gt;Then I explained what does deferred loading mean. And by examples and demos they recognized how this should work.&lt;/p&gt;  &lt;p&gt;To this point I guess I spent 1 hour and 30 minutes. Between different demos and presentation slides.&lt;/p&gt;  &lt;h4&gt;Persistence Ignorance Support {POCO}&lt;/h4&gt;  &lt;p&gt;I started the session with a question! Does anybody know what is &lt;strong&gt;Persistence Ignorance&lt;/strong&gt; mean! The general answer was NO. I already prepared myself to give a very short brief about Persistence Ignorance and the term POCO.&lt;/p&gt;  &lt;p&gt;However I had a feeling that they didn’t recognize the benefit of being Persistence Ignorant and use POCO in designing entity models. And so I guess I might spent some time preparing a talk about this topic.&lt;/p&gt;  &lt;p&gt;After defining PI and POCO I started to talk about Entity Framework support for POCO &amp;amp; PI. And that POCO entities has no dependencies on Entity Framework. I explored a bit about what is happening behind the scene and generation of proxies to support lazy loading and change tracking. Then I moved to the &lt;a href="Requirements for Using Persistence-Ignorant Objects" target="_blank"&gt;Requirements for Using Persistence-Ignorant Objects&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;Finally the demo time, I demonstrated 3 things:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Working without lazy loading and change tracking. &lt;/li&gt;    &lt;li&gt;Support lazy loading with not change tracking. Showing how entities can be modified to support that &lt;/li&gt;    &lt;li&gt;Support lazy loading and change tracking. Showing how entities can be modified to support that. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;By coincidence, I made few mistakes through the demos that violating few requirements of PI support. It was a good chance to show the audiences that following the requirements to support our requirements is important.&lt;/p&gt;  &lt;p&gt;I also debug through the code to show the audiences the proxy created behind the scene to support change tracking or lazy loading.&lt;/p&gt;  &lt;h4&gt;Code Generation Customization Using T4 templates&lt;/h4&gt;  &lt;p&gt;This was a short topic, I used the T4 POCO template provided with CTP 1 for demonstration. I explored few benefits behind code generation customization such as applying validation rules or business rules etc..&lt;/p&gt;  &lt;p&gt;Honestly I never wrote T4 template before. And it isn’t easy specially with the no intellisense support in T4 editor that is shipped out of the box with VS.NET 2010 Beta 1. So I just walked through how to use an existing T4 template –I used the POCO T4 Template-&lt;/p&gt;  &lt;h4&gt;Code Only support in Entity Framework 4.0&lt;/h4&gt;  &lt;p&gt;Moving to another new feature provided through CTP 1. Code Only Support. The name describes itself. I introduced the idea to the audiences! but again because most of the audiences were intermediate and beginner and maybe students they didn’t recognize the value of this feature.&lt;/p&gt;  &lt;p&gt;Beside it is still in CTP, many things will be introduced later to enrich this feature more and more.&lt;/p&gt;  &lt;p&gt;A demo to show this feature was important. Showing the extension APIs for creating a database from the model, mapping keys, creating/adding entities and finally commit changes to the database.&lt;/p&gt;  &lt;h4&gt;Self Tracking Entities in Entity Framework 4.0&lt;/h4&gt;  &lt;p&gt;An exciting new feature shown in the CTP 1. A Template that generate self tracking entities. First I explained what is self tracking entities, and showed to the audiences that self tracking entities are just pure POCO entities.&lt;/p&gt;  &lt;p&gt;Moved back into history the days of DataSets where it was used to transfer data over a service to client application that does modifications on it and then pass it back to the service to commit updates in data stores. Talked about how bad this can be over the wire and disadvantages of doing this.&lt;/p&gt;  &lt;p&gt;Then talked about the concept of DTOs, then moved to Self Tracking entities, which simply eliminates the need for doing manual change tracking, and eliminates the need for DTOs by using simple lightweight entities.&lt;/p&gt;  &lt;p&gt;Self Tracking entities can be generated using provided T4 template in CTP 1. But also it can be manually coded. It is matter productivity I guess.&lt;/p&gt;  &lt;p&gt;I walked through the generated code by the template to prove that the entities is totally pure POCO with no dependencies on Entity Framework infrastructure.&lt;/p&gt;  &lt;p&gt;My demo was based on &lt;a href="http://blogs.msdn.com/adonet/pages/feature-ctp-walkthrough-self-tracking-entities-for-the-entity-framework.aspx" target="_blank"&gt;the walkthrough of Self tracking entities&lt;/a&gt; posted on &lt;a href="http://blogs.msdn.com/adonet/" target="_blank"&gt;ADO.NET team blog&lt;/a&gt;. Except that it was totally different scenario. I made a simpler demo for time saving.&lt;/p&gt;  &lt;p&gt;I didn’t made the full walkthrough described in &lt;a href="http://blogs.msdn.com/adonet/" target="_blank"&gt;the post&lt;/a&gt; also for time limitation.&lt;/p&gt;  &lt;h3&gt;Conclusion&lt;/h3&gt;  &lt;p&gt;Generally I enjoyed the session and it really helped me in understanding more about Entity Framework in general and EF4 in specific. It made me admire the work done by the Entity Framework team, comparing to the current version. But a general note, audiences always ask! Why we didn’t have all this at first release! Or at least the things related to better designer experience and productivity?! Questions that personally couldn’t answer. But I consider EF v1 was a good start! and EF4 was enhanced because of community participation, comments and feedback provided about EF v1.&lt;/p&gt;  &lt;p&gt;Now it is time to start to learn about Entity Framework basics. Master them and be ready for the new version. Entity Framework won’t stop on EF4 it will evolve and will become more powerful in future. Just be ready for it, NOW!&lt;/p&gt;  &lt;p&gt;To download the presentation and demos &lt;a href="http://mosesofegypt.net/file.axd?file=EF4PreviewDotNetWorkSession.zip" target="_blank"&gt;click here&lt;/a&gt;. Demos are based on Northwind database, the script of the database is provided in the downloadable archive.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;NOTE&lt;/strong&gt;: References are provided inside the presentation on slides’ notes.&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=LTMP6fRm7VQ:wlfaB00DyJk:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=LTMP6fRm7VQ:wlfaB00DyJk:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?i=LTMP6fRm7VQ:wlfaB00DyJk:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=LTMP6fRm7VQ:wlfaB00DyJk:7Q72WNTAKBA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=7Q72WNTAKBA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=LTMP6fRm7VQ:wlfaB00DyJk:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=LTMP6fRm7VQ:wlfaB00DyJk:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?i=LTMP6fRm7VQ:wlfaB00DyJk:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/MosesOfEgyptBlog/~4/LTMP6fRm7VQ" height="1" width="1"/&gt;</description><dc:publisher xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:publisher><pingback:server xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/pingback.axd</pingback:server><pingback:target xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/post.aspx?id=4ae9bbfb-4a54-40e5-9a6d-ee8f056607d1</pingback:target><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">4</slash:comments><trackback:ping xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">http://mosesofegypt.net/trackback.axd?id=4ae9bbfb-4a54-40e5-9a6d-ee8f056607d1</trackback:ping><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/post/EntityFramework4-Beta1-Sneak-Peak-Session-at-DotNetWork-UserGroup-in-Cairo-Egypt.aspx#comment</wfw:comment><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/syndication.axd?post=4ae9bbfb-4a54-40e5-9a6d-ee8f056607d1</wfw:commentRss><feedburner:origLink>http://mosesofegypt.net/post.aspx?id=4ae9bbfb-4a54-40e5-9a6d-ee8f056607d1</feedburner:origLink></item><item><title>Introducing Entity Framework Unit Testing with TypeMock Isolator</title><link>http://feedproxy.google.com/~r/MosesOfEgyptBlog/~3/bkmkOji5tnM/post.aspx</link><category>Entity Framework</category><category>Software Design</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:creator><pubDate>Sun, 06 Sep 2009 12:58:17 PDT</pubDate><guid isPermaLink="false">http://mosesofegypt.net/post.aspx?id=21625e42-427c-45e4-b331-4252ac48799c</guid><description>&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/MHc8bRPpW-Ghk9_RbIiUxFRu6e8/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/MHc8bRPpW-Ghk9_RbIiUxFRu6e8/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/MHc8bRPpW-Ghk9_RbIiUxFRu6e8/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/MHc8bRPpW-Ghk9_RbIiUxFRu6e8/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;h3&gt;Introduction&lt;/h3&gt;  &lt;p&gt;One of the challenging things with current version of &lt;a href="http://msdn.microsoft.com/en-us/library/bb399572.aspx" target="_blank"&gt;Entity Framework&lt;/a&gt;, its leakage of testability. Which means when you build an application or module (e.g. Repositories) that depends on entity framework, it will be very hard to unit test your code isolated from Entity Framework. This might lead to conduct Integration Testing which will require a connection and interaction with underlying data store (database).&lt;/p&gt;  &lt;p&gt;You might think of using &lt;a href="http://en.wikipedia.org/wiki/Mock_object" rel="tag" target="_blank"&gt;Mocking&lt;/a&gt; to mock or fake &lt;a href="http://msdn.microsoft.com/en-us/library/bb399572.aspx" target="_blank"&gt;Entity Framework&lt;/a&gt; data store dependent calls. But sadly &lt;a href="http://code.google.com/p/moq/" rel="tag" target="_blank"&gt;Moq&lt;/a&gt; and &lt;a title="tag" href="http://ayende.com/projects/rhino-mocks.aspx" target="_blank"&gt;Rhino Mock&lt;/a&gt; mocking frameworks do not support this. And you’ll end up hitting the wall. Both frameworks are great useful and I personally use &lt;a href="http://code.google.com/p/moq/" rel="tag" target="_blank"&gt;Moq&lt;/a&gt; for a while now and very happy with it. But no one can deny limitations when exist.&lt;/p&gt;  &lt;p&gt;And personally I was able to overcome the limitation of the testability of Entity Framework while I was working in &lt;a href="http://kigg.codeplex.com/" rel="tag" target="_blank"&gt;KiGG&lt;/a&gt;&amp;#160;&lt;a href="http://msdn.microsoft.com/en-us/library/bb399572.aspx" target="_blank"&gt;Entity Framework&lt;/a&gt; based models and repositories. But done that through unnecessary code refactoring and wrappers around none mockable classes such as &lt;em&gt;sealed&lt;/em&gt; class &lt;em&gt;EntityCollection&amp;lt;T&amp;gt;&lt;/em&gt;.&lt;/p&gt;  &lt;h3&gt;Finding a solution with TypeMock Isolator&lt;/h3&gt;  &lt;p&gt;In fact there is a solution, that will save you lots of workarounds and unnecessary code refactoring. You just need a full isolation framework. &lt;a href="http://typemock.com/" rel="tag" target="_blank"&gt;TypeMock&lt;/a&gt; Isolator provides this capability. It allows to mock sealed classes and classes that have private constructors, static methods, and much more.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://typemock.com/" rel="tag" target="_blank"&gt;TypeMock isolator&lt;/a&gt; makes it easy to simulate and break the dependencies of any object in your existing code. In that way, it doesn’t force you to think about how your design might need to change. –&lt;em&gt;The Art of Unit Testing book page 132&lt;/em&gt;-&lt;/p&gt;  &lt;p&gt;So, &lt;a href="http://typemock.com/" target="_blank"&gt;TypeMock isolator&lt;/a&gt; is a perfect mate for testing code that has dependencies on Entity Framework as how I am going to show now.&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;h3&gt;The Sample, snippet from KiGG&lt;/h3&gt;  &lt;p&gt;I am going to demonstrate how to use &lt;a href="http://typemock.com/" target="_blank"&gt;TypeMock isolator&lt;/a&gt; with Entity Framework through reflected model from &lt;a href="http://kigg.codeplex.com/" rel="tag" target="_blank"&gt;KiGG&lt;/a&gt; project. Will use some code snippets from it and present single Repository class (class under test) and its &lt;a href="http://en.wikipedia.org/wiki/Unit_testing" rel="tag" target="_blank"&gt;Unit Testing&lt;/a&gt; class code. I’ll be using &lt;a href="http://xunit.codeplex.com/" rel="tag" target="_blank"&gt;xUnit&lt;/a&gt; as my &lt;a href="http://en.wikipedia.org/wiki/Unit_testing" target="_blank"&gt;Unit Testing&lt;/a&gt; framework for simplicity.&lt;/p&gt;  &lt;h3&gt;Entity Framework Generated ObjectContext&lt;/h3&gt;  &lt;p&gt;After generating part of KiGG using Entity Framework wizard, an &lt;em&gt;ObjectContext&lt;/em&gt; class is generated and it I called it &lt;em&gt;KiGGEntityContainer&lt;/em&gt;. I added/enhanced the functionality of generated class by adding few methods such as &lt;em&gt;InsertOnSubmit&amp;lt;TEntity&amp;gt;(TEntity entity)&lt;/em&gt; and &lt;em&gt;DeleteOnSubmit&amp;lt;TEntity&amp;gt;(TEntity entity)&lt;/em&gt; methods.&lt;/p&gt;  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:358c0500-54c5-4877-a2a0-380bd1d07d3b" class="wlWriterEditableSmartContent"&gt;&lt;pre name="code" class="c#:nocontrols"&gt;public void InsertOnSubmit&amp;lt;TEntity&amp;gt;(TEntity entity)
    where TEntity : EntityObject
{
    string entitySetName = GetEntitySetName(typeof(TEntity));
    AddObject(entitySetName, entity);
}

public void DeleteOnSubmit&amp;lt;TEntity&amp;gt;(TEntity entity)
    where TEntity : EntityObject
{
    DeleteObject(entity);
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;In the above &lt;em&gt;InsertOnSubmit&lt;/em&gt; method it calls a helper method &lt;em&gt;GetEntitySetName&lt;/em&gt;. This method retrieve EntitySet name from the meta data.&lt;/p&gt;

&lt;p&gt;Nothing to talk about more in this class, The test of this class is out of scope now as it will require access to EDM meta data. So for now it just directs calls to Entity Framework relevant methods &lt;em&gt;AddObject&lt;/em&gt; &amp;amp; &lt;em&gt;DeleteObject&lt;/em&gt;.&lt;/p&gt;

&lt;h3&gt;BaseRepository Class&lt;/h3&gt;

&lt;p&gt;A base generic class for all repositories. Very simple and contain basic functionality. There is nothing to test in this class as it has no logic at all. I’ll add its code for reference only and clarity.&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:40f70fed-d060-45da-ad56-fe6d84e264d0" class="wlWriterEditableSmartContent"&gt;&lt;pre name="code" class="c#:nocontrols"&gt;public abstract class BaseRepository&amp;lt;TEntity&amp;gt;
    where TEntity : EntityObject
{
    private readonly KiggEntityContainer _context;

    protected BaseRepository(KiggEntityContainer context)
    {
        _context = context;
    }

    protected internal KiggEntityContainer DataContext
    {
        get
        {
            return _context;
        }
    }

    public virtual void Add(TEntity entity)
    {
        DataContext.InsertOnSubmit(entity);
    }

    public virtual void Remove(TEntity entity)
    {
        DataContext.DeleteOnSubmit(entity as TEntity);
    }
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;/p&gt;

&lt;h3&gt;Model Class Under Test, Story class&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;Story&lt;/em&gt; is an entity model class. It has 3 navigations properties linking it with other 3 entities (User, Category &lt;img style="display: inline; margin-left: 0px; margin-right: 0px" align="right" src="http://mosesofegypt.net/image.axd?picture=WindowsLiveWriter/EFUnitTesting/KiGGStoryEntity.jpg" /&gt;and Tag).&amp;#160; &lt;/p&gt;

&lt;p&gt;Current version of Entity Framework doesn’t support transparent lazy loading. Only eager loading and explicit loading are supported. To over come this limitation, I marked the exiting navigation properties as &lt;em&gt;internal&lt;/em&gt;. And made another properties that will handle the logic of loading related end if not already loaded just as the following:&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:06b7f33f-9e11-427c-ac52-8dc263f0204d" class="wlWriterEditableSmartContent"&gt;&lt;pre name="code" class="c#:nocontrols"&gt;public partial class Story
{
    public ICollection&amp;lt;Tag&amp;gt; Tags
    {
        get
        {
            if(!TagsInternal.IsLoaded)
            {
                TagsInternal.Load();
            }
            return TagsInternal;
        }
    }

    public Category Category
    {
        get
        {
            if(!CategoryInternalReference.IsLoaded)
            {
                CategoryInternalReference.Load();
            }
            return CategoryInternalReference.Value;
        }
    }
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;The above 2 properties will need to be tested as they contain logic. What I need to test here is when &lt;em&gt;IsLoaded&lt;/em&gt; property of &lt;em&gt;EntityCollection&amp;lt;Tag&amp;gt; (TagsInternal)&lt;/em&gt; Or &lt;em&gt;EntityReference&amp;lt;Category&amp;gt; (Category)&lt;/em&gt; returns &lt;em&gt;false,&lt;/em&gt; &lt;em&gt;Load()&lt;/em&gt; method must be called. And if it return &lt;em&gt;false&lt;/em&gt;, &lt;em&gt;Load()&lt;/em&gt; method mustn’t be called. Here is the first test method –code is commented for clarification-&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:da759845-b447-4b45-a228-6b80759f8c8a" class="wlWriterEditableSmartContent"&gt;&lt;pre name="code" class="c#:nocontrols"&gt;[Fact]
public void Tags_Should_Call_Load_When_IsLoaded_Is_False()
{
    // Arrange
    var story = new Story(); //Live Object
    //Fake the return of IsLoaded property of EntityCollection&amp;lt;Tag&amp;gt;
    Isolate.WhenCalled(() =&amp;gt; story.TagsInternal.IsLoaded)
           .WillReturn(false);
    //Fake the call of Load method by ignoring the call.
    //Not doing so will throw an exception because
    //Load is supposed to load data from data store.
    Isolate.WhenCalled(() =&amp;gt; story.TagsInternal.Load())
           .IgnoreCall();
    #pragma warning disable 168
    //Act: Issue call to Tags property
    ICollection&amp;lt;Tag&amp;gt; tags = story.Tags;
    #pragma warning restore 168
    //Assert: Verify that Load method has been called.
    Isolate.Verify
           .WasCalledWithAnyArguments(()=&amp;gt;story.TagsInternal.Load());
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;What exactly TypeMock Isolator provided me here? &lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;It was impossible with any other Mocking framework to fake method calls on live object (real object not faked) or one of its properties. In this case the live object the story instance. &lt;/li&gt;

  &lt;li&gt;Faking &lt;em&gt;EntityCollection&amp;lt;T&amp;gt;&lt;/em&gt; or any of its properties or methods also impossible with other Mocking frameworks, because the class is sealed! TypeMock totally isolate me from Entity Framework by giving the ability to fake Entity Framework types and dependent method calls such as calling &lt;em&gt;IsLoaded&lt;/em&gt; property of &lt;em&gt;EntityCollection&amp;lt;T&amp;gt;&lt;/em&gt; and &lt;em&gt;Load()&lt;/em&gt; method. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;As you see, TypeMock isolates my entity class test from Entity Framework although it depends on it. The rest of this &lt;em&gt;StoryFixture&lt;/em&gt; test class is included in the attached sample. 

  &lt;br /&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;h3&gt;The Class Under Test, CategoryRepository&lt;/h3&gt;

&lt;p&gt;In this class I have 5 methods which I need to test. 3 or them concerns with LINQ to Entities queries and the other 2 are for Add and Remove, both of these 2 methods contains logic that I must be tested. For sample I’ll introduce the &lt;em&gt;Add&lt;/em&gt; method:&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:59c4f7a5-b94b-45c2-aed9-ac4a3d21d4fb" class="wlWriterEditableSmartContent"&gt;&lt;pre name="code" class="c#:nocontrols"&gt;public override void Add(Category category)
{
    if (DataContext.Categories.Any(c =&amp;gt; c.Name == categoryName))
    {
        throw new ArgumentException("Some Error Message...", "category");
    }

    category.UniqueName = UniqueNameGenerator.GenerateFrom(DataContext.Categories, category.Name);

    base.Add(category);
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;The &lt;em&gt;Add&lt;/em&gt; method checks if the name exists in the data source or not. If exists an exception should be thrown. If not a unique name to be generated for the category and then to be added to current ObjectContext for later saving.&lt;/p&gt;

&lt;p&gt;Issues with testing such method is that it depends on Entity Framework. And current version of Entity Framework will require a database hit to evaluate this query “DataContext.Categories.Any(c =&amp;gt; c.Name == categoryName)”!!&lt;/p&gt;

&lt;p&gt;Again TypeMock is a saver here. TypeMock is able to fake any ObjectContext instance. Which is not supported by other mocking engines. Faking ObjectContext instance and having the ability to fake all of its method calls and properties is really great thing. I missed that with Moq!&lt;/p&gt;

&lt;p&gt;First test for this method is to check if an exception is thrown when a new category is added and there is existing one with the same name –Code commented for clarification-:&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:c3e4893e-29de-4b5b-a5de-76632fad048c" class="wlWriterEditableSmartContent"&gt;&lt;pre name="code" class="c#:nocontrols"&gt;[Fact]
public void Add_Existing_Category_Should_Throw_ArgumentException()
{
    //Fake KiggEntityContainer -ObjectContext-
    var context = Isolate.Fake
                      	.Instance&amp;lt;KiggEntityContainer&amp;gt;(Members.ReturnRecursiveFakes);

	//Fake call to dependecy static method on static class UniqueNameGenerator
    Isolate.Fake
           .StaticMethods&amp;lt;UniqueNameGenerator&amp;gt;(Members.ReturnRecursiveFakes);

    var repo = new CategoryRepository(context);
	//Create In memory list of categories
    var inMemoryCategories = new List&amp;lt;Category&amp;gt;
               							{
                   						new Category{Name = "Dummy1"}, 
                   						new Category{Name = "Dummy2"}
               							};
    
    //Fetch existing category name
    string name = inMemoryCategories[0].Name;

	//Fake the return of ObjectQuery&amp;lt;T&amp;gt; "context.Categories"
	//Instade of using physical datastore I'm using In Memory Store
	//LINQ to Entites will be simulated with LINQ to Objects
    Isolate.WhenCalled(() =&amp;gt; context.Categories)
           .WillReturnCollectionValuesOf(inMemoryCategories.AsQueryable());

	//Assert 
    Assert.Throws(typeof(ArgumentException), 
									() =&amp;gt; repo.Add(new Category { Name = name }));
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Line 5 using fluent AAA (Arrange-Act-Assert) TypeMock APIs to fake an instance -Mock- of &lt;em&gt;KiggEntityContainer&lt;/em&gt; object context class. If you tried to do this with Moq for example you’ll desperately receive and exception that EDM meta data couldn’t be loaded. Note here that I also don’t care about the constructor parameters. I like this total isolation.&lt;/p&gt;

&lt;p&gt;Line 9 I am faking –subbing- a call to as static method on some static class. I just need to fake its call, and this test doesn't really care about its returned value&lt;/p&gt;

&lt;p&gt;Line 14 I am creating an in memory collection of categories. which will be used in replacement for underlying data store as we will see.&lt;/p&gt;

&lt;p&gt;Line 26 the most important line. In this line the powerful of TypeMock shown. Here I’m able to fake the return value of &lt;em&gt;ObjectQuery&amp;lt;Category&amp;gt;&lt;/em&gt; “context.Categories”. So simply they like says when calling context.Categories return the in memory collection of categories “inMemoryCategories”. There is a trick on this line of code to make it work; I have to call AsQueryable() of the replacement collection. If I didn’t I’ll receive and exception.&lt;/p&gt;

&lt;p&gt;Finally Line 30, Asserting that an exception is thrown when call &lt;em&gt;Add&lt;/em&gt; method of &lt;em&gt;CategoryRepository&lt;/em&gt; instance when passing a new Category with a name that match an existing category in the underlying data source.&lt;/p&gt;

&lt;p&gt;Another method in &lt;em&gt;CategoryRepository&lt;/em&gt; which is &lt;em&gt;FindByUniqueName&lt;/em&gt; is used to retrieve a category by its unique name here is the method:&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:1f565037-95fb-48c9-a67e-dd5c68f848d9" class="wlWriterEditableSmartContent"&gt;&lt;pre name="code" class="c#:nocontrols"&gt;public Category FindByUniqueName(string uniqueName)
{
	return DataContext.Categories.FirstOrDefault(c=&amp;gt;c.UniqueName == uniqueName);
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Very simple method with no logic! So what exactly I need to test here? Zooming into code, you’ll notice that I want to a category when its unique name matches a specific input. I want to test this LINQ expression that it yields the correct results.&lt;/p&gt;

&lt;p&gt;Here is the test method&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:7d8d634f-cbf9-430c-af58-33b5ddfe1b69" class="wlWriterEditableSmartContent"&gt;&lt;pre name="code" class="c#:nocontrols"&gt;[Fact]
public void FindById_Should_Return_Correct_Category()
{
    //_context is a fake ObjectContext instance
    var repository = new CategoryRepository(_context);
    
    //In memory collection store of categories
    List&amp;lt;Category&amp;gt; inMemoryCategories = new List&amp;lt;Category&amp;gt;
               				{
                   			new Category{Id=Guid.NewGuid(),Name = "Dummy1"}, 
                   			new Category{Id=Guid.NewGuid(),Name = "Dummy2"}
               				};
    
    Guid id = inMemoryCategories[0].Id;

    //Fake ObjectQuery&amp;lt;Category&amp;gt;
    //Must call AsQueryable() extension in order for this to work
    Isolate.WhenCalled(() =&amp;gt; _context.Categories)
           .WillReturnCollectionValuesOf(inMemoryCategories.AsQueryable());
    
    //Act
    Category found = repository.FindById(id);

    //Assert
    Assert.Equal(id, found.Id);
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;Again I am replacing (faking) the return of &lt;em&gt;ObjectQuery&amp;lt;Category&amp;gt;&lt;/em&gt; with in memory list of categories. This way when &lt;em&gt;_context.Categories&lt;/em&gt; is called an in memory &lt;em&gt;IQueryable&amp;lt;Category&amp;gt;&lt;/em&gt; will be returned. The LINQ will be evaluated as LINQ to Object an not as LINQ to Entities. Because LINQ to Entities will require a database hit which I want to avoid.&lt;/p&gt;

&lt;p&gt;This way TypeMock Isolator provided an isolation from Entity Framework, although my component is totally dependent on Entity Framework. This is impossible with other mocking framework which shows the strength of TypeMock in this point.&lt;/p&gt;

&lt;p&gt;Code for this sample downloadable from &lt;a href="http://mosesofegypt.net/file.axd?file=EntityFrameworkUnitTesting.zip" rel="enclosure" target="_blank"&gt;here&lt;/a&gt;. &lt;em&gt;Note that I didn’t include &lt;/em&gt;&lt;a href="http://typemock.com/" target="_blank"&gt;&lt;em&gt;TypeMock&lt;/em&gt;&lt;/a&gt;&lt;em&gt; assemblies which you should download from &lt;/em&gt;&lt;a href="http://typemock.com/Downloads.php" rel="tag" target="_blank"&gt;&lt;em&gt;here&lt;/em&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;Conclusion&lt;/h3&gt;

&lt;p&gt;There is a white paper published by TypeMock with comparing different mocking framework to TypeMock itself. This comparison white paper is downloadable from &lt;a href="http://www.typemock.com/files/Docs/Typemock%20-%20Comparison%20with%20Competitors1.pdf" rel="enclosure" target="_blank"&gt;here&lt;/a&gt;. Also there is an open source project to compare between mocking frameworks which you can check it out &lt;a href="http://code.google.com/p/mocking-frameworks-compare/" rel="tag" target="_blank"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;I’ve been working with different mocking framework for a while now. Moq is my favourite free open source one. I also worked a little with Rhino Mock, a great framework however at the time I was working Moq, I didn’t feel comfortable with record &amp;amp; replay mode of Rhino Mock. Beside Moq was very simple and very easy to learn. Rhino Mock is going to rock in its upcoming version 4.0 you can read about its plans &lt;a href="http://ayende.com/Blog/archive/2009/09/03/planning-for-rhino-mocks-4.0.aspx" rel="tag" target="_blank"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;TypeMock is the most powerful mocking framework I ever seen so far. as I mentioned earlier &lt;a href="http://typemock.com/" rel="tag" target="_blank"&gt;TypeMock isolator&lt;/a&gt; makes it easy to simulate and break the dependencies of any object in your existing code. In that way, it doesn’t force you to think about how your design might need to change. –&lt;em&gt;The Art of Unit Testing book page 132&lt;/em&gt;-.&lt;/p&gt;

&lt;p&gt;TypeMock can isolate almost everything, they even have specific release for unit testing with SharePoint which so far no tool compete on this with it.&lt;/p&gt;

&lt;p&gt;TypeMock is commercial, However, they provide &lt;a href="http://www.typemock.com/free_open_source_license_form.php" target="_blank"&gt;free license for open source projects&lt;/a&gt;. And for MVPs, they are eligible for a free version TypeMock Isolator Enterprise Edition! MVPs can check it out &lt;a href="http://www.typemock.com/mvp.php" target="_blank"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;&lt;a href="http://mosesofegypt.net/file.axd?file=EntityFrameworkUnitTesting.zip" rel="enclosure" target="_blank"&gt;Download the Sample&lt;/a&gt;&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=bkmkOji5tnM:BwWG3diTJjI:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=bkmkOji5tnM:BwWG3diTJjI:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?i=bkmkOji5tnM:BwWG3diTJjI:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=bkmkOji5tnM:BwWG3diTJjI:7Q72WNTAKBA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=7Q72WNTAKBA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=bkmkOji5tnM:BwWG3diTJjI:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=bkmkOji5tnM:BwWG3diTJjI:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?i=bkmkOji5tnM:BwWG3diTJjI:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/MosesOfEgyptBlog/~4/bkmkOji5tnM" height="1" width="1"/&gt;</description><dc:publisher xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:publisher><pingback:server xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/pingback.axd</pingback:server><pingback:target xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/post.aspx?id=21625e42-427c-45e4-b331-4252ac48799c</pingback:target><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">14</slash:comments><trackback:ping xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">http://mosesofegypt.net/trackback.axd?id=21625e42-427c-45e4-b331-4252ac48799c</trackback:ping><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/post/Introducing-Entity-Framework-Unit-Testing-with-TypeMock-Isolator.aspx#comment</wfw:comment><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/syndication.axd?post=21625e42-427c-45e4-b331-4252ac48799c</wfw:commentRss><feedburner:origLink>http://mosesofegypt.net/post.aspx?id=21625e42-427c-45e4-b331-4252ac48799c</feedburner:origLink></item><item><title>Multiple database support with Entity Framework</title><link>http://feedproxy.google.com/~r/MosesOfEgyptBlog/~3/srKJytQwZDM/post.aspx</link><category>Entity Framework</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:creator><pubDate>Tue, 18 Aug 2009 12:46:42 PDT</pubDate><guid isPermaLink="false">http://mosesofegypt.net/post.aspx?id=196434e1-c387-4eb3-9a48-1952bbdd1af2</guid><description>&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/Yip9YKSc9BdecbgJvnHUZQydpSI/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/Yip9YKSc9BdecbgJvnHUZQydpSI/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/Yip9YKSc9BdecbgJvnHUZQydpSI/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/Yip9YKSc9BdecbgJvnHUZQydpSI/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;h2&gt;Introduction&lt;/h2&gt;  &lt;p&gt;One of the features introduced in &lt;a href="http://msdn.microsoft.com/en-us/library/bb399572.aspx" target="_blank"&gt;Entity Framework&lt;/a&gt; is being database independent. Which mean each database provider can support &lt;a href="http://msdn.microsoft.com/en-us/library/bb399572.aspx" target="_blank"&gt;Entity Framework&lt;/a&gt; by implementing its provider.&lt;/p&gt;  &lt;p&gt;This feature allows you build applications independent from the underplaying database provider. In this post I’m going to show how to build an application that support multiple databases using same conceptual model made by &lt;a href="http://msdn.microsoft.com/en-us/library/bb399572.aspx" target="_blank"&gt;Entity Framework&lt;/a&gt;.&lt;/p&gt;  &lt;h2&gt;Entity Framework providers&lt;/h2&gt;  &lt;p&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/bb399572.aspx" target="_blank"&gt;Entity Framework&lt;/a&gt; is database independent. Each database provider could have its own &lt;a href="http://msdn.microsoft.com/en-us/library/bb399572.aspx" target="_blank"&gt;Entity Framework&lt;/a&gt; provider. Currently there are several database provider who support the current version of &lt;a href="http://msdn.microsoft.com/en-us/library/bb399572.aspx" target="_blank"&gt;Entity Framework&lt;/a&gt; that is released with .Net 3.5 SP1.&lt;/p&gt;  &lt;p&gt;A list of &lt;a href="http://msdn.microsoft.com/en-us/library/bb399572.aspx" target="_blank"&gt;Entity Framework&lt;/a&gt; providers can be found &lt;a href="http://msdn.microsoft.com/en-us/data/dd363565.aspx" rel="tag" target="_blank"&gt;here&lt;/a&gt;.&lt;/p&gt;  &lt;h2&gt;Entity Framework multiple database support sample&lt;/h2&gt;  &lt;p&gt;In this post, I am going to demonstrate a sample application (based on northwind database) that is going to support both SQL Server database engine and &lt;a href="http://www.mysql.com/" target="_blank"&gt;MySQL&lt;/a&gt; database engine.&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;h2&gt;MySQL Entity Framework provider (connector/net)&lt;/h2&gt;  &lt;p&gt;&lt;a href="http://dev.mysql.com/downloads/connector/net/6.0.html" rel="tag" target="_blank"&gt;MySQL Entity Framework provider&lt;/a&gt; I am going to use is &lt;a href="http://dev.mysql.com/downloads/connector/net/6.0.html" target="_blank"&gt;connector/net&lt;/a&gt; ADO.NET provider for &lt;a href="http://www.mysql.com/" target="_blank"&gt;MySQL&lt;/a&gt;. It is a free provider and open source built by &lt;a href="http://www.mysql.com/" target="_blank"&gt;MySQL&lt;/a&gt; .Net data provider team. The version I am using is a modified version (by me) of connector/net 6.0.3. At the time of writing this post current release is 6.0.4.&lt;/p&gt;  &lt;h2&gt;How to prepare your Entity Data Model for multi-database support?&lt;/h2&gt;  &lt;p&gt;In order to keep your conceptual model (CSDL) static and ready to be used with different databases you should make sure that your database schema is the same across all database engine you plan to support.&lt;/p&gt;  &lt;p&gt;For example, Northwind database schema in SQL Server is the same as Northwind database in &lt;a href="http://www.mysql.com/" target="_blank"&gt;MySQL&lt;/a&gt;. There are differences in data types, for example uniqueidentifier doesn’t exists in current version of &lt;a href="http://www.mysql.com/" target="_blank"&gt;MySQL&lt;/a&gt;, however there is a replacement which could be varbinary(16). Also data types might differ in names but there representation in .Net is the same, for example there is bit in SQL server and boolean -tinyint- in &lt;a href="http://www.mysql.com/" target="_blank"&gt;MySQL&lt;/a&gt; can be mapped to Boolean -bool- in .Net. Schema includes views and stored procedures/user defined functions (names, parameters and return results)&lt;/p&gt;  &lt;p&gt;As conclusion, you have to maintain your database schema across any engine you wish to use to keep your CSDL untouchable. However change in your storage schema in EDM (SSDL) is mandatory as we are going to see later.&lt;/p&gt;  &lt;h2&gt;Steps support multiple database providers using Entity Framework&lt;/h2&gt;  &lt;h4&gt;Modifying the SSDL&lt;/h4&gt;  &lt;p&gt;First step would be preparing your database on the provider you wish to work with. In my case it is MySQL. Script of northwind database on MySQL is &lt;a href="http://mosesofegypt.net/file.axd?file=EFMutliDatabaseSupport.zip" rel="enclosure"&gt;attached&lt;/a&gt; with this post.&lt;/p&gt;  &lt;p&gt;Next step is to modify your SSDL! If you are using VS.Net 2008 SP1 Entity Framework designer then your probably got a EDMX file for the generated EDM. the EDMX combines all CSDL,SSDL and MSL in it. You need just to have another SSDL file for your new database under MySQL.&lt;/p&gt;  &lt;p&gt;To proceed with this, just create another file with and call it for example &lt;strong&gt;Northwind.MySQL.ssdl&lt;/strong&gt;. Set its &lt;em&gt;Copy to Output Directory&lt;/em&gt; option to &lt;em&gt;Copy Always&lt;/em&gt;. Then add the following at the top of the new document (XML root):     &lt;br /&gt;&lt;strong&gt;&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot;?&amp;gt;&lt;/strong&gt;     &lt;br /&gt;Then follow the following steps to extract (copy) SSDL from the generated EDMX&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Right click on your EDMX file “&lt;em&gt;Northwind.edmx&lt;/em&gt;” and select “&lt;strong&gt;Open With…&lt;/strong&gt;” from the context menu. &lt;/li&gt;    &lt;li&gt;From “&lt;strong&gt;Open With&lt;/strong&gt;” dialog select XML Editor (make sure you already saved your EDMX). An XML view of your EDMX will appear. &lt;/li&gt;    &lt;li&gt;Find an XML comment &lt;em&gt;&amp;lt;!--SSDL content --&amp;gt;&lt;/em&gt; where you will find underneath it a &lt;strong&gt;StorageModels&lt;/strong&gt; element. &lt;/li&gt;    &lt;li&gt;Copy the content of &lt;strong&gt;Schema&lt;/strong&gt; element under &lt;strong&gt;StorageModels&lt;/strong&gt; element (without &lt;strong&gt;StorageModels&lt;/strong&gt; element) &lt;/li&gt;    &lt;li&gt;Past what you just copied into &lt;strong&gt;Northwind.MySQL.ssdl&lt;/strong&gt; &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;After you got your copy of SSDL file you’ll need to modify it. Lets walkthrough where the modification should take place.&lt;/p&gt;  &lt;p&gt;The &lt;strong&gt;Schema&lt;/strong&gt; element contain several attributes. 2 of them should be changes to a new values. &lt;strong&gt;&lt;em&gt;Provider&lt;/em&gt;&lt;/strong&gt; and &lt;strong&gt;ProviderManifestToken&lt;/strong&gt; attributes.&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;&lt;strong&gt;Provider&lt;/strong&gt; attribute specify the underlying .Net data provider name that should be used for this storage schema (SSDL). So change its value to “&lt;strong&gt;MySql.Data.MySqlClient&lt;/strong&gt;”. &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/bb896311.aspx" rel="tag" target="_blank"&gt;ProviderManifestToken&lt;/a&gt;&lt;/strong&gt; used to load the provider manifest for offline scenarios.There is no specific schema for the token; it is up to the provider to choose the minimum information needed to identify a manifest without having to open a connection to storage. You’ll notice in most cases it shows a version of the underlying database engine. So in MySQL case it should be “&lt;strong&gt;MySQL5&lt;/strong&gt;”. &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;The final output of Schema element should look like this:&lt;/p&gt;  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:a9a97980-bb2f-4d5a-977d-01e885d25c5b" class="wlWriterEditableSmartContent"&gt;&lt;pre name="code" class="xml:nocontrols"&gt;&amp;lt;Schema Namespace="NorthwindModel.Store" Alias="Self" 
   Provider="MySql.Data.MySqlClient" 
   ProviderManifestToken="MySQL5" 
   xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" 
   xmlns="http://schemas.microsoft.com/ado/2006/04/edm/ssdl"&amp;gt;...
&amp;lt;/Schema&amp;gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;The next changes are related to the storage schema (schema name and data types). &lt;/p&gt;

&lt;p&gt;On each &lt;strong&gt;EntitySet&lt;/strong&gt; element there is an attribute called &lt;strong&gt;schema&lt;/strong&gt;. In case of SQL Server this attribute is set to the related table schema. In MySQL you just need to set this attribute to the name your database.&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:f02434cc-8292-4495-940b-f565603be10b" class="wlWriterEditableSmartContent"&gt;&lt;pre name="code" class="xml:nocontrols"&gt;&amp;lt;EntitySet Name="Categories" .... Schema="northwind" /&amp;gt;&lt;/pre&gt;&lt;/div&gt;

&lt;br /&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;font size="1"&gt;Note: in the above code snippet part of code is omitted for clarification.&lt;/font&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Now under each &lt;strong&gt;EntityType&lt;/strong&gt; element there are several &lt;strong&gt;Property&lt;/strong&gt; elements. Each &lt;strong&gt;Property&lt;/strong&gt; element maps to a database table column with the same name. And of course should be of the same data type. That is why there is a &lt;strong&gt;Type&lt;/strong&gt; attribute for each &lt;strong&gt;Property&lt;/strong&gt; element.&lt;/p&gt;

&lt;p&gt;Sometimes (depending on provider mapped data types) you’ll need to change this &lt;strong&gt;Type&lt;/strong&gt; attribute for several &lt;strong&gt;Property&lt;/strong&gt; elements. For example MySQL provider doesn’t recognize the data type ntext which supported by SQL Server. However another data type could be used such as MEDIUMTEXT or LONGTEXT.&lt;/p&gt;

&lt;p&gt;You should correct such things in your &lt;strong&gt;Schema&lt;/strong&gt; &lt;strong&gt;EntityType&lt;/strong&gt;s &lt;strong&gt;Properties&lt;/strong&gt;. Happy that Nothwind isn’t complicated at all and most of the data types used with it are common between both engines. I just had to change few types.&lt;/p&gt;

&lt;p&gt;Now we are done with SSDL modification, and time to move to Connection String.&lt;/p&gt;

&lt;h4&gt;Modifying Connection String&lt;/h4&gt;

&lt;p&gt;I left this to the end. Changing connection string would the most easy task. I highly recommend to read about &lt;a href="http://msdn.microsoft.com/en-us/library/cc716756.aspx" rel="tag" target="_blank"&gt;Connection Strings in Entity Framework&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The connection string generated to you would be something like this:&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:6900ec6f-ebcf-423c-bcef-3d49561d1b23" class="wlWriterEditableSmartContent"&gt;&lt;pre name="code" class="xml:nocontrols"&gt;&amp;lt;connectionStrings&amp;gt;
 &amp;lt;add name="Northwind" 
  connectionString="metadata=res://*/NorthwindModel.csdl|res://*/NorthwindModel.ssdl|res://*/NorthwindModel.msl;provider=System.Data.SqlClient;provider connection string=&amp;amp;quot;Data Source=.\SQLExpress;Initial Catalog=Northwind;Integrated Security=True;&amp;amp;quot;" 
  providerName="System.Data.EntityClient" /&amp;gt;
  &amp;lt;/connectionStrings&amp;gt;&lt;/pre&gt;&lt;/div&gt;
A change to connection string is mandatory to specify different ssdl file, provider and provider connection string. All these information is provided above as a value to &lt;strong&gt;connectionString&lt;/strong&gt; attribute of &lt;strong&gt;add&lt;/strong&gt; element.

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;A modified Connection string would be like this:&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:0c7e4078-02ab-474c-a3c6-7612b2914297" class="wlWriterEditableSmartContent"&gt;&lt;pre name="code" class="c#:nocontrols"&gt;&amp;lt;add name="NorthwindEntitiesMySQL"
 connectionString="metadata=Northwind.MySql.ssdl|res://*/NorthwindModel.csdl|res://*/NorthwindModel.msl;provider=MySql.Data.MySqlClient;provider connection string=&amp;amp;quot;server=localhost;user id=root;password=Pa$$w0rd;persist security info=True;database=northwind&amp;amp;quot;" 
 providerName="System.Data.EntityClient" /&amp;gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Note that &lt;strong&gt;&lt;em&gt;&lt;u&gt;metadata&lt;/u&gt;&lt;/em&gt;&lt;/strong&gt; value is changed. It now points to &lt;strong&gt;Nothwind.MySQL.ssdl&lt;/strong&gt; file that is not part of assembly resource, but a file on the same folder of the executing assembly. Also &lt;strong&gt;&lt;u&gt;provider&lt;/u&gt;&lt;/strong&gt; value change to &lt;strong&gt;MySql.Data.MySqlClient&lt;/strong&gt; and &lt;em&gt;&lt;strong&gt;&lt;u&gt;provider connection string&lt;/u&gt;&lt;/strong&gt;&lt;/em&gt; is changed to “&lt;strong&gt;server=localhost;user id=root;password=Pa$$w0rd;persist security info=True;database=northwind&lt;/strong&gt;”.&lt;/p&gt;

&lt;p&gt;Note that you also can choose to make your &lt;strong&gt;Northwind.MySQL.ssdl&lt;/strong&gt; as part of assembly resources by changing the &lt;em&gt;Build action&lt;/em&gt; of the file to be &lt;em&gt;Embedded Resource&lt;/em&gt; and &lt;em&gt;Copy to Output Directory&lt;/em&gt; option to &lt;em&gt;Do not copy&lt;/em&gt;. In this case your metadata value will be “&lt;strong&gt;metadata=res://*/Northwind.MySql.ssdl|res://*/NorthwindModel.csdl|res://*/NorthwindModel.msl&lt;/strong&gt;”.&lt;/p&gt;

&lt;p&gt;Now have a look at the &lt;a href="http://mosesofegypt.net/file.axd?file=EFMutliDatabaseSupport.zip" rel="enclosure"&gt;attached sample project&lt;/a&gt;. Notice that there is no change in code that access the entity framework, just changing the connection string to use another one.&lt;/p&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;Being database independent is a great feature that comes out of the box with Entity Framework. Being able to switch to another database engine without touching your code is one big feature I admire myself. Just changes in SSDL and connection string and you are done to go live on another database with your application.&lt;/p&gt;

&lt;p&gt;We already applied this practically with &lt;a href="http://kigg.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=28200" rel="tag" target="_blank"&gt;latest release of KiGG&lt;/a&gt;. Now &lt;a href="http://kigg.codeplex.com/" rel="tag" target="_blank"&gt;KiGG&lt;/a&gt; supports repositories and models that are implemented with current version of Entity Framework. &lt;a href="http://kigg.codeplex.com/" rel="tag" target="_blank"&gt;KiGG&lt;/a&gt; -with appreciation to Entity Framework- supports both SQL Server and MySQL. No code change –check it yourself-&lt;/p&gt;

&lt;p&gt;Feel free to &lt;a href="http://kigg.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=28200" rel="tag" target="_blank"&gt;download KiGG&lt;/a&gt; or the &lt;a href="http://mosesofegypt.net/file.axd?file=EFMutliDatabaseSupport.zip" rel="enclosure" target="_blank"&gt;attached sample&lt;/a&gt; to explore this cool feature.&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=srKJytQwZDM:kpQ8JqX0fAM:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=srKJytQwZDM:kpQ8JqX0fAM:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?i=srKJytQwZDM:kpQ8JqX0fAM:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=srKJytQwZDM:kpQ8JqX0fAM:7Q72WNTAKBA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=7Q72WNTAKBA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=srKJytQwZDM:kpQ8JqX0fAM:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=srKJytQwZDM:kpQ8JqX0fAM:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?i=srKJytQwZDM:kpQ8JqX0fAM:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/MosesOfEgyptBlog/~4/srKJytQwZDM" height="1" width="1"/&gt;</description><dc:publisher xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:publisher><pingback:server xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/pingback.axd</pingback:server><pingback:target xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/post.aspx?id=196434e1-c387-4eb3-9a48-1952bbdd1af2</pingback:target><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">16</slash:comments><trackback:ping xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">http://mosesofegypt.net/trackback.axd?id=196434e1-c387-4eb3-9a48-1952bbdd1af2</trackback:ping><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/post/Multiple-database-support-with-Entity-Framework.aspx#comment</wfw:comment><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/syndication.axd?post=196434e1-c387-4eb3-9a48-1952bbdd1af2</wfw:commentRss><feedburner:origLink>http://mosesofegypt.net/post.aspx?id=196434e1-c387-4eb3-9a48-1952bbdd1af2</feedburner:origLink></item><item><title>Introducing Entity Framework v1 in DotNetWork User Group in Cairo Egypt</title><link>http://feedproxy.google.com/~r/MosesOfEgyptBlog/~3/JC07vHinISQ/post.aspx</link><category>Entity Framework</category><category>Learning &amp; Certifications</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:creator><pubDate>Sat, 18 Jul 2009 02:09:23 PDT</pubDate><guid isPermaLink="false">http://mosesofegypt.net/post.aspx?id=4948112d-83a1-4455-b4ea-826d1896d1c8</guid><description>&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/42Q_1CkNb4s6u1QJUSqOV6sGKx4/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/42Q_1CkNb4s6u1QJUSqOV6sGKx4/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/42Q_1CkNb4s6u1QJUSqOV6sGKx4/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/42Q_1CkNb4s6u1QJUSqOV6sGKx4/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;p&gt;&lt;a href="http://maximumcs.wordpress.com/" rel="contact" target="_blank"&gt;Bishoy Ghaly&lt;/a&gt; &amp;amp; me made an introductory presentation about &lt;a href="http://msdn.microsoft.com/en-us/library/bb399572.aspx" target="_blank"&gt;Entity Framework&lt;/a&gt; for the first time in &lt;a href="http://dotnetwork.org/" target="_blank"&gt;DotNetWork&lt;/a&gt; User Group in Cairo, Egypt –Saturday 18th July-&lt;/p&gt;  &lt;p&gt;After a survey we made in June we discovered that an introductory session to Entity Framework is a must. So we prepared this 3 hours session -level 100- to introduce Entity Framework to the audiences.&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;Our agenda:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;History of ADO.Net &lt;/li&gt;    &lt;li&gt;Object Relational Mapping {ORM} &lt;/li&gt;    &lt;li&gt;What is Entity Framework? &lt;/li&gt;    &lt;li&gt;Entity Framework Architecture &lt;/li&gt;    &lt;li&gt;Entity Data Model {EDM} &lt;/li&gt;    &lt;li&gt;Entity Client &amp;amp; Object Services &lt;/li&gt;    &lt;li&gt;LINQ to Entities &amp;amp; Entity SQL {eSQL} &lt;/li&gt;    &lt;li&gt;Load Related Objects &lt;/li&gt;    &lt;li&gt;&lt;a href="http://mosesofegypt.net/?tag=/ef-inheritance" target="_blank"&gt;Inheritance in Entity Framework&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;Entity Framework providers and multiple database support &lt;/li&gt;    &lt;li&gt;Entity Framework Limitations (if time permits) &lt;/li&gt;    &lt;li&gt;External Tools (if time permits) &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;The presentation had around 10 Demos. All of them are meant for introducing Entity Framework in basic level.&lt;/p&gt;  &lt;p&gt;We have a plan to blog about few topics mentioned in the above agenda. Also these posts will be very basic as it will be related to the presentation.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://www.slideshare.net/bishoyghaly/introducing-entity-framework" rel="tag" target="_blank"&gt;Session presentation (Power Point)&lt;/a&gt;, presenters’ script and demos are available for download (&lt;a href="http://mosesofegypt.net/file.axd?file=IntroducingEF.zip" rel="enclosure"&gt;Click here&lt;/a&gt;).&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=JC07vHinISQ:Umi2oI4h-hw:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=JC07vHinISQ:Umi2oI4h-hw:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?i=JC07vHinISQ:Umi2oI4h-hw:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=JC07vHinISQ:Umi2oI4h-hw:7Q72WNTAKBA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=7Q72WNTAKBA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=JC07vHinISQ:Umi2oI4h-hw:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=JC07vHinISQ:Umi2oI4h-hw:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?i=JC07vHinISQ:Umi2oI4h-hw:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/MosesOfEgyptBlog/~4/JC07vHinISQ" height="1" width="1"/&gt;</description><dc:publisher xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:publisher><pingback:server xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/pingback.axd</pingback:server><pingback:target xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/post.aspx?id=4948112d-83a1-4455-b4ea-826d1896d1c8</pingback:target><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">4</slash:comments><trackback:ping xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">http://mosesofegypt.net/trackback.axd?id=4948112d-83a1-4455-b4ea-826d1896d1c8</trackback:ping><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/post/Introducing-Entity-Framework-v1-in-DotNetWork-User-Group-in-Cairo-Egypt.aspx#comment</wfw:comment><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/syndication.axd?post=4948112d-83a1-4455-b4ea-826d1896d1c8</wfw:commentRss><feedburner:origLink>http://mosesofegypt.net/post.aspx?id=4948112d-83a1-4455-b4ea-826d1896d1c8</feedburner:origLink></item><item><title>Silverlight 3 is out with SDK and Tools with useful links</title><link>http://feedproxy.google.com/~r/MosesOfEgyptBlog/~3/PBuStVBbo70/post.aspx</link><category>Silverlight</category><category>Bookmark</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:creator><pubDate>Fri, 10 Jul 2009 18:01:09 PDT</pubDate><guid isPermaLink="false">http://mosesofegypt.net/post.aspx?id=7fcbacbc-c520-4651-a877-6adb501f3159</guid><description>&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/tCsRR1GtHAFOlKkdmuf5J2FeGW4/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/tCsRR1GtHAFOlKkdmuf5J2FeGW4/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/tCsRR1GtHAFOlKkdmuf5J2FeGW4/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/tCsRR1GtHAFOlKkdmuf5J2FeGW4/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;p&gt;&lt;a href="http://www.silverlight.net" target="_blank"&gt;Silverlight&lt;/a&gt; 3 is out, &lt;a href="http://weblogs.asp.net/scottgu" target="_blank"&gt;Scott Guthrie&lt;/a&gt; &lt;a href="http://weblogs.asp.net/scottgu/archive/2009/07/10/silverlight-3-released.aspx" rel="tag" target="_blank"&gt;Announced&lt;/a&gt; that on his blog. As I was started to upgrade my client, I thought it would be useful to search for the SDK and Silverlight 3 VS.NET tools too. Thought to share the following quick links for Silverlight 3&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://www.microsoft.com/silverlight/resources/technical-resources/default.aspx" target="_blank"&gt;Silverlight technical resource&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://go.microsoft.com/fwlink/?linkid=150228" target="_blank"&gt;Silverlight 3 for Developers&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://go.microsoft.com/fwlink/?LinkID=143571" target="_blank"&gt;Silverlight Tools for Visual Studio.Net 2008 SP1&lt;/a&gt;&amp;#160;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://go.microsoft.com/fwlink/?LinkID=157102" target="_blank"&gt;Microsoft® Silverlight™ 3 SDK&lt;/a&gt; (&lt;em&gt;Silverlight 3 SDK is installed by Microsoft Silverlight Tools automatically&lt;/em&gt;)&lt;/li&gt;    &lt;li&gt;&lt;a href="http://go.microsoft.com/fwlink/?LinkId=144350" target="_blank"&gt;Microsoft Silverlight 3 Offline Documentation&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=PBuStVBbo70:481rZmCuFNE:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=PBuStVBbo70:481rZmCuFNE:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?i=PBuStVBbo70:481rZmCuFNE:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=PBuStVBbo70:481rZmCuFNE:7Q72WNTAKBA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=7Q72WNTAKBA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=PBuStVBbo70:481rZmCuFNE:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=PBuStVBbo70:481rZmCuFNE:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?i=PBuStVBbo70:481rZmCuFNE:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/MosesOfEgyptBlog/~4/PBuStVBbo70" height="1" width="1"/&gt;</description><dc:publisher xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:publisher><pingback:server xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/pingback.axd</pingback:server><pingback:target xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/post.aspx?id=7fcbacbc-c520-4651-a877-6adb501f3159</pingback:target><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">1</slash:comments><trackback:ping xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">http://mosesofegypt.net/trackback.axd?id=7fcbacbc-c520-4651-a877-6adb501f3159</trackback:ping><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/post/Silverlight-3-is-out-with-SDK-and-Tools-with-useful-links.aspx#comment</wfw:comment><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/syndication.axd?post=7fcbacbc-c520-4651-a877-6adb501f3159</wfw:commentRss><feedburner:origLink>http://mosesofegypt.net/post.aspx?id=7fcbacbc-c520-4651-a877-6adb501f3159</feedburner:origLink></item><item><title>KiGG support for Entity Framework and MySQL</title><link>http://feedproxy.google.com/~r/MosesOfEgyptBlog/~3/lN_tRnhRr4Y/post.aspx</link><category>Entity Framework</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:creator><pubDate>Tue, 07 Jul 2009 12:39:37 PDT</pubDate><guid isPermaLink="false">http://mosesofegypt.net/post.aspx?id=3a7236f3-29d1-441f-96a5-42878b6b14d1</guid><description>&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/8sBhR9tZLNFG9T1oky3oH_7M8ko/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/8sBhR9tZLNFG9T1oky3oH_7M8ko/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/8sBhR9tZLNFG9T1oky3oH_7M8ko/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/8sBhR9tZLNFG9T1oky3oH_7M8ko/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;h2&gt;Introduction&lt;/h2&gt;  &lt;p&gt;&lt;a href="http://kigg.codeplex.com/" rel="tag" target="_blank"&gt;KiGG&lt;/a&gt; is a Web 2.0 style social news web application developed in Microsoft supported technologies. It is an &lt;a href="http://kigg.codeplex.com/" target="_blank"&gt;open source project&lt;/a&gt; hosted on &lt;a href="http://www.codeplex.com/" target="_blank"&gt;CodePlex&lt;/a&gt;. It is live and running as &lt;a href="http://dotnetshoutout.com/" target="_blank"&gt;DotNetShoutout.com&lt;/a&gt;.&lt;/p&gt;  &lt;h2&gt;KiGG and Entity Framework&lt;/h2&gt;  &lt;p&gt;On May 2009, I’ve completed the implementation of &lt;a href="http://msdn.microsoft.com/en-us/library/bb399572.aspx" target="_blank"&gt;Entity Framework&lt;/a&gt; support on KiGG. KiGG design was very flexible to plug another repository implementation other than LINQ to SQL. So basically now KiGG comes with 2 repository flavours, LINQ to SQL and Entity Framework.&lt;/p&gt;  &lt;p&gt;Read about &lt;a href="http://kigg.codeplex.com/Wiki/View.aspx?title=KiGG%20Entity%20Framework%20Configuration" rel="tag" target="_blank"&gt;how to configure your KiGG application to use Entity Framework&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;h2&gt;KiGG and MySQL&lt;/h2&gt;  &lt;p&gt;After &lt;a href="http://msdn.microsoft.com/en-us/library/bb399572.aspx" target="_blank"&gt;Entity Framework&lt;/a&gt; implementation is completed, I wanted to gain benefit of it. I wanted to support multiple databases using &lt;a href="http://msdn.microsoft.com/en-us/library/bb399572.aspx" target="_blank"&gt;Entity Framework&lt;/a&gt; without changing the code!&lt;/p&gt;  &lt;p&gt;Entity Framework Entity Data Model (EDM) separate storage model (SSDL) from conceptual model (CSDL). The Conceptual model mustn’t be touched under any circumstances. Only storage model (SSDL) is subject to change because it is couple with underlying data provider and database engine.&lt;/p&gt;  &lt;p&gt;My first candidate database engine was MySQL. And successfully added support to MySQL using &lt;a href="http://dev.mysql.com/downloads/connector/net/6.0.html"&gt;MySQL Connector/net&lt;/a&gt;.Net Data Provider for MySQL (free) and &lt;a href="http://www.devart.com/dotconnect/mysql/"&gt;Devart .Net Data Provider for MySQL&lt;/a&gt; (commercial)&lt;/p&gt;  &lt;p&gt;Read about &lt;a href="http://kigg.codeplex.com/Wiki/View.aspx?title=Configuring%20KiGG%20to%20use%20MySQL%20Database%20through%20Entity%20Framework" rel="tag" target="_blank"&gt;how to configure KiGG to use MySQL database&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;IMPORTANT NOTE:&lt;/strong&gt;    &lt;br /&gt;I modified MySQL Connector/net code to fix few issues related to LINQ to Entities, Entity SQL and Guid support. KiGG do not support the provider released by MySQL Connector/net, instead use the modified version.&lt;/p&gt;  &lt;p&gt;Soon I will blog about how to target different database engines using Entity Framework in single application so &lt;a href="http://feeds2.feedburner.com/MosesOfEgyptBlog" target="_blank"&gt;stay tuned&lt;/a&gt;.&lt;/p&gt;  &lt;h2&gt;KiGG Entity Framework and MySQL Support How-To:&lt;/h2&gt;  &lt;p&gt;I wrote couple of articles -detailed- on project wiki as documentation. Feel free to reference those articles in order to configure your KiGG application to use Entity Framework and MySQL:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://kigg.codeplex.com/Wiki/View.aspx?title=KiGG%20Entity%20Framework%20Configuration" rel="tag" target="_blank"&gt;How to configure KiGG to use Entity Framework Repository&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://kigg.codeplex.com/Wiki/View.aspx?title=Configuring%20KiGG%20to%20use%20MySQL%20Database%20through%20Entity%20Framework" rel="tag" target="_blank"&gt;Configuring KiGG to use MySQL Database through Entity Framework&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=lN_tRnhRr4Y:3UmmsWpDYKU:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=lN_tRnhRr4Y:3UmmsWpDYKU:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?i=lN_tRnhRr4Y:3UmmsWpDYKU:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=lN_tRnhRr4Y:3UmmsWpDYKU:7Q72WNTAKBA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=7Q72WNTAKBA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=lN_tRnhRr4Y:3UmmsWpDYKU:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=lN_tRnhRr4Y:3UmmsWpDYKU:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?i=lN_tRnhRr4Y:3UmmsWpDYKU:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/MosesOfEgyptBlog/~4/lN_tRnhRr4Y" height="1" width="1"/&gt;</description><dc:publisher xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:publisher><pingback:server xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/pingback.axd</pingback:server><pingback:target xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/post.aspx?id=3a7236f3-29d1-441f-96a5-42878b6b14d1</pingback:target><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">4</slash:comments><trackback:ping xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">http://mosesofegypt.net/trackback.axd?id=3a7236f3-29d1-441f-96a5-42878b6b14d1</trackback:ping><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/post/KiGG-support-for-Entity-Framework-and-MySQL.aspx#comment</wfw:comment><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/syndication.axd?post=3a7236f3-29d1-441f-96a5-42878b6b14d1</wfw:commentRss><feedburner:origLink>http://mosesofegypt.net/post.aspx?id=3a7236f3-29d1-441f-96a5-42878b6b14d1</feedburner:origLink></item><item><title>Microsoft ADO.NET Entity Framework Feature CTP 1 Post Beta 1</title><link>http://feedproxy.google.com/~r/MosesOfEgyptBlog/~3/xSvEYt4u_Dw/post.aspx</link><category>Entity Framework</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:creator><pubDate>Tue, 30 Jun 2009 09:38:26 PDT</pubDate><guid isPermaLink="false">http://mosesofegypt.net/post.aspx?id=99477bc0-99e6-4f55-b654-3c587e06e1da</guid><description>&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/AS8g8TcHjmEReED-tXedydh-mLo/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/AS8g8TcHjmEReED-tXedydh-mLo/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/AS8g8TcHjmEReED-tXedydh-mLo/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/AS8g8TcHjmEReED-tXedydh-mLo/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;p&gt;Microsoft &lt;a href="http://blogs.msdn.com/adonet/" target="_blank"&gt;ADO.Net team&lt;/a&gt; released (this month June 2009) a set of features that build on top of Entity Framework 4.0 Beta 1     &lt;br /&gt;The features included in this CTP are : &lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;&lt;a href="http://blogs.msdn.com/adonet/archive/2009/06/22/feature-ctp-walkthrough-self-tracking-entities-for-entity-framework.aspx" rel="tag" target="_blank"&gt;Templates for Self-Tracking Entities (N-Tier support)&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a href="http://blogs.msdn.com/adonet/archive/2009/06/22/feature-ctp-walkthrough-poco-templates-for-entity-framework.aspx" rel="tag" target="_blank"&gt;Templates for POCO (Plain Old CLR Objects) Entities&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a href="http://blogs.msdn.com/adonet/archive/2009/06/22/feature-ctp-walkthrough-code-only-for-entity-framework.aspx" rel="tag" target="_blank"&gt;Code-Only Programming Model&lt;/a&gt; that allows you to write Entity Data Model based applications without requiring external artifacts&lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;CTP can be downloaded &lt;a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=7FD7164E-9E73-43F7-90AB-5B2BF2577AC9&amp;amp;displaylang=en" rel="enclosure" target="_blank"&gt;here&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Enjoy it.&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=xSvEYt4u_Dw:8_4ujnbZT-A:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=xSvEYt4u_Dw:8_4ujnbZT-A:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?i=xSvEYt4u_Dw:8_4ujnbZT-A:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=xSvEYt4u_Dw:8_4ujnbZT-A:7Q72WNTAKBA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=7Q72WNTAKBA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=xSvEYt4u_Dw:8_4ujnbZT-A:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=xSvEYt4u_Dw:8_4ujnbZT-A:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?i=xSvEYt4u_Dw:8_4ujnbZT-A:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/MosesOfEgyptBlog/~4/xSvEYt4u_Dw" height="1" width="1"/&gt;</description><dc:publisher xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:publisher><pingback:server xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/pingback.axd</pingback:server><pingback:target xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/post.aspx?id=99477bc0-99e6-4f55-b654-3c587e06e1da</pingback:target><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">0</slash:comments><trackback:ping xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">http://mosesofegypt.net/trackback.axd?id=99477bc0-99e6-4f55-b654-3c587e06e1da</trackback:ping><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/post/Microsoft-ADONET-Entity-Framework-Feature-CTP-1-Post-Beta-1.aspx#comment</wfw:comment><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/syndication.axd?post=99477bc0-99e6-4f55-b654-3c587e06e1da</wfw:commentRss><feedburner:origLink>http://mosesofegypt.net/post.aspx?id=99477bc0-99e6-4f55-b654-3c587e06e1da</feedburner:origLink></item><item><title>Entity Framework minimum permission considerations</title><link>http://feedproxy.google.com/~r/MosesOfEgyptBlog/~3/0QS0OR3eGCI/post.aspx</link><category>Entity Framework</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:creator><pubDate>Thu, 21 May 2009 11:50:04 PDT</pubDate><guid isPermaLink="false">http://mosesofegypt.net/post.aspx?id=1d205f3b-23aa-48bb-87c4-0c5f69dfeee6</guid><description>&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/ohOvNRQTXbBP--IMxaWLSF2k4uE/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/ohOvNRQTXbBP--IMxaWLSF2k4uE/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/ohOvNRQTXbBP--IMxaWLSF2k4uE/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/ohOvNRQTXbBP--IMxaWLSF2k4uE/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;h2&gt;Introduction&lt;/h2&gt;  &lt;p&gt;While working with &lt;a href="http://msdn.microsoft.com/en-us/library/bb399572.aspx" target="_blank"&gt;Entity Framework&lt;/a&gt; v1 during &lt;a href="http://kigg.codeplex.com/" rel="tag" target="_blank"&gt;KiGG&lt;/a&gt; implementation of &lt;a href="http://msdn.microsoft.com/en-us/library/bb399572.aspx" target="_blank"&gt;Entity Framework&lt;/a&gt; repositories, I decided to test &lt;a href="http://kigg.codeplex.com/" rel="tag" target="_blank"&gt;KiGG&lt;/a&gt; for partial trust environment. Particularly &lt;a href="http://msdn.microsoft.com/en-us/library/ms998341.aspx" target="_blank"&gt;Medium Trust&lt;/a&gt; support. Will not go through whether &lt;a href="http://kigg.codeplex.com/" rel="tag" target="_blank"&gt;KiGG&lt;/a&gt; currently support medium trust or not in it current or upcoming version, but I will go through one of the reasons why &lt;a href="http://kigg.codeplex.com/" rel="tag" target="_blank"&gt;KiGG&lt;/a&gt; currently might not support &lt;a href="http://msdn.microsoft.com/en-us/library/ms998341.aspx" target="_blank"&gt;medium trust&lt;/a&gt;. It is because MY implementation of &lt;a href="http://msdn.microsoft.com/en-us/library/bb399572.aspx" target="_blank"&gt;Entity Framework&lt;/a&gt;. Note that I am saying MY, because Entity Framework application can run on &lt;a href="http://msdn.microsoft.com/en-us/library/ms998341.aspx" target="_blank"&gt;medium trust&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;h3&gt;Running Entity Framework applications with minimum permissions&lt;/h3&gt;  &lt;p&gt;The following is a snippet from MSDN documentation &lt;a href="http://msdn.microsoft.com/en-us/library/cc716760.aspx" rel="tag" target="_blank"&gt;Security Considerations (Entity Framework)&lt;/a&gt;:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;The following code access permissions are the minimum permissions your Entity Framework application needs:&lt;/p&gt;    &lt;ul&gt;     &lt;li&gt;       &lt;p&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.security.permissions.fileiopermission.aspx"&gt;FileIOPermission&lt;/a&gt;: &lt;a href="http://msdn.microsoft.com/en-us/library/system.security.permissions.fileiopermissionaccess.write.aspx"&gt;Write&lt;/a&gt; to open the specified metadata files or &lt;a href="http://msdn.microsoft.com/en-us/library/system.security.permissions.fileiopermissionaccess.pathdiscovery.aspx"&gt;PathDiscovery&lt;/a&gt; to search a directory for metadata files.&lt;/p&gt;     &lt;/li&gt;      &lt;li&gt;       &lt;p&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.security.permissions.reflectionpermission.aspx"&gt;&lt;strong&gt;ReflectionPermission&lt;/strong&gt;&lt;/a&gt;&lt;strong&gt;: &lt;/strong&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.security.permissions.reflectionpermissionflag.restrictedmemberaccess.aspx"&gt;&lt;strong&gt;RestrictedMemberAccess&lt;/strong&gt;&lt;/a&gt;&lt;strong&gt; to support LINQ to Entities queries&lt;/strong&gt;.&lt;/p&gt;     &lt;/li&gt;      &lt;li&gt;       &lt;p&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.transactions.distributedtransactionpermission.aspx"&gt;DistributedTransactionPermission&lt;/a&gt;: &lt;a href="http://msdn.microsoft.com/en-us/library/system.security.permissions.permissionstate.unrestricted.aspx"&gt;Unrestricted&lt;/a&gt; to enlist in a &lt;a href="http://msdn.microsoft.com/en-us/library/system.transactions.aspx"&gt;System.Transactions&lt;/a&gt; &lt;a href="http://msdn.microsoft.com/en-us/library/system.transactions.transaction.aspx"&gt;Transaction&lt;/a&gt;.&lt;/p&gt;     &lt;/li&gt;      &lt;li&gt;       &lt;p&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.security.permissions.securitypermission.aspx"&gt;SecurityPermission&lt;/a&gt;: &lt;a href="http://msdn.microsoft.com/en-us/library/system.security.permissions.securitypermissionflag.serializationformatter.aspx"&gt;SerializationFormatter&lt;/a&gt; to serialize exceptions by using the &lt;a href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.iserializable.aspx"&gt;ISerializable&lt;/a&gt; interface. &lt;/p&gt;     &lt;/li&gt;      &lt;li&gt;       &lt;p&gt;Permission to open a database connection and execute commands against the database, such as &lt;a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlclientpermission.aspx"&gt;SqlClientPermission&lt;/a&gt; for a SQL Server database.&lt;/p&gt;     &lt;/li&gt;   &lt;/ul&gt; &lt;/blockquote&gt;  &lt;p&gt;What I am going to focus on is the 2nd point (in &lt;strong&gt;bold&lt;/strong&gt;). Entity Framework request &lt;a href="http://msdn.microsoft.com/en-us/library/system.security.permissions.reflectionpermission.aspx"&gt;ReflectionPermission&lt;/a&gt; with &lt;a href="http://msdn.microsoft.com/en-us/library/system.security.permissions.reflectionpermissionflag.restrictedmemberaccess.aspx"&gt;RestrictedMemberAccess&lt;/a&gt; to support LINQ to Entities queries. You need to know what is &lt;a href="http://msdn.microsoft.com/en-us/library/system.security.permissions.reflectionpermissionflag.restrictedmemberaccess.aspx"&gt;RestrictedMemberAccess&lt;/a&gt;.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.security.permissions.reflectionpermissionflag.restrictedmemberaccess.aspx"&gt;RestrictedMemberAccess&lt;/a&gt; allows access to non-public members, with the restriction that the grant set of the non-public members must be equal to, or a subset of, the grant set of the code that accesses the non-public members.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;In &lt;a href="http://msdn.microsoft.com/en-us/library/ms998341.aspx" target="_blank"&gt;Medium Trust&lt;/a&gt; environment, &lt;a href="http://msdn.microsoft.com/en-us/library/system.security.permissions.reflectionpermission.aspx"&gt;ReflectionPermission&lt;/a&gt; is granted but with &lt;a href="http://msdn.microsoft.com/en-us/library/system.security.permissions.reflectionpermissionflag.restrictedmemberaccess.aspx"&gt;RestrictedMemberAccess&lt;/a&gt;. So what does that means?!&lt;/p&gt;  &lt;p&gt;It simply means if you have an Entity Class with a non-public property and you are using this property in any of your LINQ to Entities queries, the following exception will be your punishment.&lt;/p&gt;  &lt;p&gt;&lt;em&gt;SecurityException: Request for the permission of type 'System.Security.Permissions.ReflectionPermission failed&lt;/em&gt;&lt;/p&gt;  &lt;h2&gt;How to enable your Entity Framework implementation to run on medium trust environment?&lt;/h2&gt;  &lt;p&gt;I think you already guessed the answer. Just make your Entity Classes’ properties that will participate in LINQ to Entities queries public. I would recommend also to make the entities itself public as well.&lt;/p&gt;  &lt;h2&gt;Conclusion&lt;/h2&gt;  &lt;p&gt;Don’t think of this as a limitation of Entity Framework, myself I don’t think so. I also expect this behaviour in LINQ to SQL too as. I guess I should correct this in KiGG by marking used properties in queries as public.&lt;/p&gt;  &lt;p&gt;I made a sample to demonstrate the exception and its cause. Feel free to &lt;a href="http://mosesofegypt.net/file.axd?file=EntityFrameworkPartialTrust.zip" rel="enclosure" target="_blank"&gt;download&lt;/a&gt; the sample and explore it.&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=0QS0OR3eGCI:siTkCddYS6c:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=0QS0OR3eGCI:siTkCddYS6c:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?i=0QS0OR3eGCI:siTkCddYS6c:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=0QS0OR3eGCI:siTkCddYS6c:7Q72WNTAKBA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=7Q72WNTAKBA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=0QS0OR3eGCI:siTkCddYS6c:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=0QS0OR3eGCI:siTkCddYS6c:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?i=0QS0OR3eGCI:siTkCddYS6c:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/MosesOfEgyptBlog/~4/0QS0OR3eGCI" height="1" width="1"/&gt;</description><dc:publisher xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:publisher><pingback:server xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/pingback.axd</pingback:server><pingback:target xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/post.aspx?id=1d205f3b-23aa-48bb-87c4-0c5f69dfeee6</pingback:target><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">4</slash:comments><trackback:ping xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">http://mosesofegypt.net/trackback.axd?id=1d205f3b-23aa-48bb-87c4-0c5f69dfeee6</trackback:ping><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/post/Entity-Framework-minimum-permission-considerations.aspx#comment</wfw:comment><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/syndication.axd?post=1d205f3b-23aa-48bb-87c4-0c5f69dfeee6</wfw:commentRss><feedburner:origLink>http://mosesofegypt.net/post.aspx?id=1d205f3b-23aa-48bb-87c4-0c5f69dfeee6</feedburner:origLink></item><item><title>Entity Framework 4 Persistence-Ignorance First Look</title><link>http://feedproxy.google.com/~r/MosesOfEgyptBlog/~3/2bqQE7d2nDg/post.aspx</link><category>Entity Framework</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:creator><pubDate>Wed, 20 May 2009 14:36:20 PDT</pubDate><guid isPermaLink="false">http://mosesofegypt.net/post.aspx?id=c6d0d9a6-671d-4473-bd6d-f54640b8425e</guid><description>&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/yOHp_kDfdhsNJl0Dxwk6HfWNZ24/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/yOHp_kDfdhsNJl0Dxwk6HfWNZ24/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/yOHp_kDfdhsNJl0Dxwk6HfWNZ24/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/yOHp_kDfdhsNJl0Dxwk6HfWNZ24/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;h2&gt;Introduction:&lt;/h2&gt;  &lt;p&gt;From the moment I put my hands on Visual Studio.Net 2010 Beta 1 and I’m targeting EF4 –&lt;a href="http://msdn.microsoft.com/en-us/library/bb399572.aspx" target="_blank"&gt;Entity Framework&lt;/a&gt; 4- as I was very excited to checkout the new cool feature of it.&lt;/p&gt;  &lt;p&gt;Here I am going to highlight my first look at Persistence-Ignorance support in EF4.&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;h2&gt;EF4 Support for POCO classes:&lt;/h2&gt;  &lt;p&gt;Well, what I can say?! it as simple as writing something like this:&lt;/p&gt;  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:f637a396-3fe7-445d-af37-ccb23be32707" class="wlWriterEditableSmartContent"&gt;&lt;pre name="code" class="c#:nocontrols"&gt;public class Category
{
    public int CategoryID { get; set; }
    public string CategoryName { get; set; }
    public string Description { get; set; }
    public ICollection&amp;lt;Product&amp;gt; Products { get; private set; }
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;The above code is your POCO class. The class name exactly matches the Entity Type in CSDL and so all the properties.&lt;/p&gt;

&lt;p&gt;So what about ObjectContext?! I implemented my own simple one for demonstration:&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:13417a7d-332a-41f4-8d6a-f378eb7db546" class="wlWriterEditableSmartContent"&gt;&lt;pre name="code" class="c#:nocontrols"&gt;public class NorthwindObjectContext : ObjectContext
{
    public NorthwindObjectContext(string connectionString)
        : base(connectionString, "NorthwindContext")
    {
    }

    private IObjectSet&amp;lt;Category&amp;gt; _categorySet;

    public IObjectSet&amp;lt;Category&amp;gt; CategorySet 
    {
        get 
        {
            if (_categorySet == null)
            {
                _categorySet = CreateObjectSet&amp;lt;Category&amp;gt;();
            }
            return _categorySet;
        }
    }
}&lt;/pre&gt;&lt;/div&gt;

&lt;br /&gt;On a simple console application I made the following. 

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:73d527f2-6cc8-40a9-a26b-8f7f39814005" class="wlWriterEditableSmartContent"&gt;&lt;pre name="code" class="c#:nocontrols"&gt;public static void Main(string[] args)
{
 using (var context = new NorthwindObjectContext("name=NorthwindContext"))
 {
	try
	{
		var category = context.CategorySet.First();
		Console.WriteLine(category.CategoryName);
	}
	catch (Exception ex)
	{
		Console.Write(ex.ToString());
	}
 }
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;And to checkout also that it supports Compiled Queries I made one&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:22d4234f-e5cf-4ccc-9ce2-7883ac561fcf" class="wlWriterEditableSmartContent"&gt;&lt;pre name="code" class="c#:nocontrols"&gt;private readonly static Func&amp;lt;NorthwindObjectContext, int, Category&amp;gt; FindCategoryById = 
            CompiledQuery.Compile&amp;lt;NorthwindObjectContext, int, Category&amp;gt;(
            (db,id) =&amp;gt; db.CategorySet.SingleOrDefault(c=&amp;gt;c.CategoryID==id));&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;And the run it&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:11df3fbf-17a8-4d5b-82a6-2ded2ebb471c" class="wlWriterEditableSmartContent"&gt;&lt;pre name="code" class="c#:nocontrols"&gt;var category = FindCategoryById.Invoke(context,2);
Console.WriteLine(category.CategoryName);&lt;/pre&gt;&lt;/div&gt;

&lt;br /&gt;And that was great for a first touch. It became more easier. 

&lt;p&gt;&lt;strong&gt;About Change Tracking &amp;amp; Deferred Loading:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;One important thing I must clarify about my POCO class above (the &lt;em&gt;Category&lt;/em&gt; class). &lt;strong&gt;This class doesn’t support change tracking or transparent deferred loading (lazy loading)&lt;/strong&gt;. So for example if you tried to get &lt;em&gt;Products&lt;/em&gt; property of &lt;em&gt;Category&lt;/em&gt; class, it will return null.&lt;/p&gt;

&lt;p&gt;And if you modified the category instance and just call context.SaveChanges(true); this will have no effect because the category instance is already not tracked for any change.&lt;/p&gt;

&lt;p&gt;Of course these is a reason of that. The reason is stated on the requirement of Persistence-Ignorant Objects on MSDN to enable POCO classes to support self-change tracking as well as deferred loading. Here is what MSDN states:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Class Definition Requirements&lt;/strong&gt; &lt;/p&gt;

  &lt;p&gt;To be able to generate the proxy objects that are required by Object Services to track changes and to support deferred loading of related objects, custom data classes must meet the following requirements. (&lt;a href="http://msdn.microsoft.com/en-us/library/dd468057(VS.100).aspx" target="_blank"&gt;read more about class POCO class definition requirements in EF4&lt;/a&gt;) &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;So for this sample I will not implement these requirements (&lt;a href="http://feeds2.feedburner.com/MosesOfEgyptBlog" target="_blank"&gt;keep tuned for next posts&lt;/a&gt;) But I will show how to explicitly load related objects and submit changes.&lt;/p&gt;

&lt;p&gt;Explicit loading of related objects using newly introduced method &lt;a href="http://msdn.microsoft.com/en-us/library/dd412913(VS.100).aspx" target="_blank"&gt;LoadProperty&lt;/a&gt;:&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:1194020c-f461-4fbb-b2fb-399b547d5225" class="wlWriterEditableSmartContent"&gt;&lt;pre name="code" class="c#:nocontrols"&gt;private static void FetchSample()
{
 	using (var context = new NorthwindObjectContext("name=NorthwindContext"))
 	{
		try
		{
			//By default it is false
			context.ContextOptions.DeferredLoadingEnabled = true;
        
			//using compiled queries
			var category = FindCategoryById.Invoke(context, 2);

			//Explicit Loading of Products
			context.LoadProperty&amp;lt;Category&amp;gt;(category, c =&amp;gt; c.Products);
			Console.WriteLine("{0} has {1} products", 
													category.CategoryName, 
													category.Products.Count);

			category = context.CategorySet.First();
			Console.WriteLine(category.CategoryName);
		}
		catch (Exception ex)
		{
			Console.Write(ex.ToString());
		}
	}
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;And for submitting changes:&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:015dc09f-41ca-4130-8777-f3f71bc30609" class="wlWriterEditableSmartContent"&gt;&lt;pre name="code" class="c#:nocontrols"&gt;private static void UpdateSample()
{
	using (var context = new NorthwindObjectContext("name=NorthwindContext"))
	{
		try
		{
			context.ContextOptions.ProxyCreationEnabled = true;
			var category = FindCategoryById.Invoke(context, 1); //context.CategorySet.First();
            
			Console.WriteLine("{0}:{1}",category.CategoryName, category.Description);
			category.Description = category.Description + "[Updated]";
            
			//No generated proxy classes =&amp;gt; No tracking
			//Call DetectChanges(); Explicitly
			//Ref: http://msdn.microsoft.com/en-us/library/dd456848(VS.100).aspx
			context.DetectChanges();    
			context.SaveChanges();
			Console.WriteLine("{0}:{1}", category.CategoryName, category.Description);
		}
		catch (Exception ex)
		{
			Console.Write(ex.ToString());
		}
	}
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;At line 16 I am calling &lt;a href="http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.detectchanges(VS.100).aspx" target="_blank"&gt;DetectChanges&lt;/a&gt; method. There is an alternate way which is to call &lt;a href="http://msdn.microsoft.com/en-us/library/dd395500%28VS.100%29.aspx"&gt;SaveChanges(SaveOptions)&lt;/a&gt; and supply a value of &lt;a href="http://msdn.microsoft.com/en-us/library/system.data.objects.saveoptions%28VS.100%29.aspx"&gt;DetectChangesBeforeSave&lt;/a&gt;. In this case &lt;a href="http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.detectchanges(VS.100).aspx" target="_blank"&gt;DetectChanges&lt;/a&gt; is automatically called before changes are persisted to the data source.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Conclusion:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;EF4 is really far away of EF v1. Totally brand new product. It will beat the popularity LINQ to SQL had earlier especially after all new added features to it. &lt;/p&gt;

&lt;p&gt;I will blog soon about deferred loading and change tracking with EF4 after applying POCO class definition requirements.&lt;/p&gt;

&lt;p&gt;&lt;a title="Entity Framework 4 Persistence-Ignorance First Look Sample" href="http://mosesofegypt.net/file.axd?file=EntityFramework4Demo-PI-FirstLook.zip" rel="enclosure"&gt;Download the sample&lt;/a&gt; (&lt;strong&gt;&lt;em&gt;requires VS.Net 2010 Beta 1&lt;/em&gt;&lt;/strong&gt;)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;NOTE:&lt;/strong&gt; The sample is using &lt;strong&gt;Northwind&lt;/strong&gt; database which is not attached. You can download it from Microsoft web site&lt;/p&gt;

&lt;p&gt;MSDN References:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/dd456853%28VS.100%29.aspx"&gt;Persistence-Ignorant Objects (Entity Framework)&lt;/a&gt; &lt;/li&gt;

  &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/dd468057%28VS.100%29.aspx"&gt;Requirements for Using Persistence-Ignorant Objects (Entity Framework)&lt;/a&gt; &lt;/li&gt;

  &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/dd456855%28VS.100%29.aspx"&gt;Loading Related Persistence-Ignorant Objects (Entity Framework)&lt;/a&gt; &lt;/li&gt;

  &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/dd456848%28VS.100%29.aspx"&gt;Tracking Changes in Persistence-Ignorant Objects (Entity Framework)&lt;/a&gt; &lt;/li&gt;

  &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/dd456875%28VS.100%29.aspx"&gt;Managing Relationships between Persistence-Ignorant Objects (Entity Framework)&lt;/a&gt; &lt;/li&gt;

  &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/dd456872(VS.100).aspx" target="_blank"&gt;How to: Define Custom Persistence-Ignorant Objects (Entity Framework)&lt;/a&gt; &lt;/li&gt;

  &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/dd468073(VS.100).aspx" target="_blank"&gt;How to: Create a Persistence-Ignorant Object (Entity Framework)&lt;/a&gt; &lt;/li&gt;

  &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/dd456854%28VS.100%29.aspx"&gt;How to: Manually Detect Changes in Persistence-Ignorant Objects (Entity Framework)&lt;/a&gt; &lt;/li&gt;

  &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/dd456846(VS.100).aspx" target="_blank"&gt;How to: Enable Deferred Loading of Related Objects (Entity Framework)&lt;/a&gt; &lt;/li&gt;

  &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/dd468074%28VS.100%29.aspx"&gt;How to: Explicitly Load Persistence-Ignorant Objects (Entity Framework)&lt;/a&gt; &lt;/li&gt;

  &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/dd456829(VS.100).aspx" target="_blank"&gt;How to: Change Relationships Between Persistence-Ignorant Objects (Entity Framework)&lt;/a&gt; &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a title="ADO.NET Team Blog" href="http://blogs.msdn.com/adonet/" target="_blank"&gt;ADO.NET Team Blog&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href="http://blogs.msdn.com/adonet/archive/2009/05/21/poco-in-the-entity-framework-part-1-the-experience.aspx" rel="tag" target="_blank"&gt;POCO in the Entity Framework: Part 1 - The Experience&lt;/a&gt; (High Recommendation to read)&lt;/li&gt;

  &lt;li&gt;&lt;a title="Sneak Preview: Persistence Ignorance and POCO in Entity Framework 4.0" href="http://blogs.msdn.com/adonet/archive/2009/05/11/sneak-preview-persistence-ignorance-and-poco-in-entity-framework-4-0.aspx" rel="tag" target="_blank"&gt;Sneak Preview: Persistence Ignorance and POCO in Entity Framework 4.0&lt;/a&gt; &lt;/li&gt;

  &lt;li&gt;&lt;a title="Sneak Preview: Deferred Loading in Entity Framework 4.0" href="http://blogs.msdn.com/adonet/archive/2009/05/12/sneak-preview-deferred-loading-in-entity-framework-4-0.aspx" rel="tag" target="_blank"&gt;Sneak Preview: Deferred Loading in Entity Framework 4.0&lt;/a&gt;&lt;/li&gt;

  &lt;li&gt;&lt;a title="Sneak Preview: Entity Framework 4.0 Testability Improvements" href="http://blogs.msdn.com/adonet/archive/2009/05/18/sneak-preview-entity-framework-4-0-testability-improvements.aspx" rel="tag" target="_blank"&gt;Sneak Preview: Entity Framework 4.0 Testability Improvements&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=2bqQE7d2nDg:jbEH7H-Br6o:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=2bqQE7d2nDg:jbEH7H-Br6o:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?i=2bqQE7d2nDg:jbEH7H-Br6o:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=2bqQE7d2nDg:jbEH7H-Br6o:7Q72WNTAKBA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=7Q72WNTAKBA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=2bqQE7d2nDg:jbEH7H-Br6o:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=2bqQE7d2nDg:jbEH7H-Br6o:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?i=2bqQE7d2nDg:jbEH7H-Br6o:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/MosesOfEgyptBlog/~4/2bqQE7d2nDg" height="1" width="1"/&gt;</description><dc:publisher xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:publisher><pingback:server xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/pingback.axd</pingback:server><pingback:target xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/post.aspx?id=c6d0d9a6-671d-4473-bd6d-f54640b8425e</pingback:target><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">7</slash:comments><trackback:ping xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">http://mosesofegypt.net/trackback.axd?id=c6d0d9a6-671d-4473-bd6d-f54640b8425e</trackback:ping><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/post/Entity-Framework-4-Persistence-Ignorance-First-Look.aspx#comment</wfw:comment><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/syndication.axd?post=c6d0d9a6-671d-4473-bd6d-f54640b8425e</wfw:commentRss><feedburner:origLink>http://mosesofegypt.net/post.aspx?id=c6d0d9a6-671d-4473-bd6d-f54640b8425e</feedburner:origLink></item><item><title>Introducing DataLoadOptions for Entity Framework ObjectContext</title><link>http://feedproxy.google.com/~r/MosesOfEgyptBlog/~3/xg2R9_KKOUY/post.aspx</link><category>Entity Framework</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:creator><pubDate>Sat, 16 May 2009 09:05:10 PDT</pubDate><guid isPermaLink="false">http://mosesofegypt.net/post.aspx?id=79250d43-882f-4de3-bae6-92876179dd3d</guid><description>&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/1tndfZHpQCImbWaxMnZAjp4z8TI/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/1tndfZHpQCImbWaxMnZAjp4z8TI/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/1tndfZHpQCImbWaxMnZAjp4z8TI/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/1tndfZHpQCImbWaxMnZAjp4z8TI/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;p&gt;On my previous post “&lt;a href="http://mosesofegypt.net/post/What-about-DataLoadOptions-for-Entity-Framework-ObjectContext.aspx" rel="tag"&gt;What about DataLoadOptions for Entity Framework ObjectContext?&lt;/a&gt;” I was suggesting another way to define eager loading for &lt;a href="http://msdn.microsoft.com/en-us/library/bb399572.aspx" target="_blank"&gt;Entity Framework&lt;/a&gt;. In this post I will introduce my DataLoadOptions for &lt;a href="http://msdn.microsoft.com/en-us/library/bb399572.aspx" target="_blank"&gt;Entity Framework&lt;/a&gt; ObjectContext.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;The beginning:&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Actually Eager and Lazy loading on Entity Framework is not that much fun like in Linq to Sql. However this is going to be improved in EF4.&lt;/p&gt;  &lt;p&gt;Here I will focus on eager loading and my slight improvement to define eager loading in Entity Framework. When I start to think about, I wanted something simple and pretty close to the way Linq to Sql work. In Linq to Sql it is the &lt;a href="http://msdn.microsoft.com/en-us/library/system.data.linq.dataloadoptions.aspx" target="_blank"&gt;DataLoadOptions&lt;/a&gt; that helps you define eager loading before start using Linq to Sql DataContext.&lt;/p&gt;  &lt;p&gt;So I started to explore the &lt;a href="http://msdn.microsoft.com/en-us/library/system.data.linq.dataloadoptions.aspx" target="_blank"&gt;DataLoadOptions&lt;/a&gt; code using reflector, to better understand how it works and how it helps Linq to Sql define eager loading.&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;The Idea:&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;The idea was very simple here it is:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;First I need to register the entity members that I wish to pre load when retrieving root entity. This should be achieved with this syntax d&lt;em&gt;ataLoadOptions.LoadWith&amp;lt;Product&amp;gt;(p=&amp;gt;p.Category)&lt;/em&gt;. My DataLoadOptions should store that I want to pre load product’s category whenever I attempt to load a product record.&lt;/li&gt;    &lt;li&gt;I should provide my ObjectContext with a DataLoadOptions instance:      &lt;br /&gt;&lt;em&gt;context.LoadOptions = dataLoadOptions;&lt;/em&gt;&lt;/li&gt;    &lt;li&gt;Before trying to retrieve any EntitySet (&lt;em&gt;context.ProductSet&lt;/em&gt;) I should start prepare the query to include all registered preloaded members using &lt;em&gt;ObjectContext.Include&lt;/em&gt; method.      &lt;br /&gt;&lt;/li&gt;    &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:371964ef-e31b-4f31-9bf1-c211f8c08f04" class="wlWriterEditableSmartContent"&gt;&lt;pre name="code" class="c#:nocontrols"&gt;public partial class NorthwindObjectContext: ObjectContext
{
	public ObjectQuery&amp;lt;Product&amp;gt; ProductSet
  {
  	get
		{
			if (_productSet==null)
			{
				_productSet  = ApplyDataLoadOptions&amp;lt;Product&amp;gt;("ProductSet");
			}
			return _productSet;
		}
	}

	private ObjectQuery&amp;lt;TEntity&amp;gt; ApplyDataLoadOptions&amp;lt;TEntity&amp;gt;(string queryString)
	{
		var query = CreateQuery&amp;lt;TEntity&amp;gt;(queryString);

		if (LoadOptions != null)
		{
			var members = LoadOptions.GetPreloadedMembers&amp;lt;TEntity&amp;gt;();

			foreach (var member in members)
			{
				query = query.Include(member.Name);
			}
		}
		return query;
	}
}&lt;/pre&gt;&lt;/div&gt;
&lt;/ol&gt;

&lt;p&gt;You should know that this idea is close the one in Linq to Sql but it is not exactly the same.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Implementation:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;I had &lt;a href="http://mosesofegypt.net/file.axd?file=EntityFrameworkDataLoadOptionDemo.zip" rel="enclosure" target="_blank"&gt;attached&lt;/a&gt; a sample code to this post that include the implementation of DataLoadOptions class, to save space I will let that to you to explore.&lt;/p&gt;

&lt;p&gt;Part of the implementation is to have &lt;em&gt;ApplyDataLoadOptions&lt;/em&gt; method (or call it whatever you want) as in line 15 above. This method is using &lt;em&gt;GerPreloadedMembers&amp;lt;TEntity&amp;gt;&lt;/em&gt; method of DataLoadOptions instance to get all registered properties for eager loading. Then it loops through those members and call &lt;em&gt;Include&lt;/em&gt; method passing member/property name, finally found a good usage of having &lt;em&gt;Include&lt;/em&gt; method accepting string.&lt;/p&gt;

&lt;p&gt;Here is a sample usage code:&lt;/p&gt;

&lt;p&gt;
  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:6950aebb-c8d0-433a-87aa-460c9f569b8a" class="wlWriterEditableSmartContent"&gt;&lt;pre name="code" class="c#:nocontrols"&gt;using(var context = new NorthwindObjectContext())
{
    var loadOptions = new DataLoadOptions();
    loadOptions.LoadWith&amp;lt;Product&amp;gt;(p =&amp;gt; p.Category);
    loadOptions.LoadWith&amp;lt;Product&amp;gt;(p =&amp;gt; p.Supplier);
    
    context.LoadOptions = loadOptions;
    
    var queryString = context.ProductSet.ToTraceString();
		var products = context.ProductSet;
		foreach(var product in products)
		{
			Console.WriteLine(product.Category.Name);
		}
    Console.WriteLine(queryString);
}&lt;/pre&gt;&lt;/div&gt;
&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hints:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The following is not allowed in Linq to Sql:&lt;/p&gt;

&lt;p&gt;
  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:0fb9c03a-6972-4a77-b678-0234cc76fa30" class="wlWriterEditableSmartContent"&gt;&lt;pre name="code" class="c#:nocontrols"&gt;loadOptions.LoadWith&amp;lt;Product&amp;gt;(p=&amp;gt;p.Category);  
loadOptions.LoadWith&amp;lt;Category&amp;gt;(c=&amp;gt;c.Products); &lt;/pre&gt;&lt;/div&gt;
&lt;/p&gt;

&lt;p&gt;This should throw an exception. In Entity Framework this is not the case it will work. Not because this implementation is much better than the on in Linq to Sql, but because it is different and work differently than Linq to Sql.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Conclusion:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;EF4 is promising, and I highly recommend that you keep tuned about what &lt;a href="http://blogs.msdn.com/adonet/" rel="tag" target="_blank"&gt;ADO.NET on Entity Framework doing&lt;/a&gt;. So far I didn’t read about what they are going to provide for Eager Loading, but I expect that soon.&lt;/p&gt;

&lt;p&gt;I have plugged this implementation of DataLoadOptions into &lt;a href="http://kigg.codeplex.com/" target="_blank"&gt;KiGG&lt;/a&gt; EF implementation. I wanted to keep both Linq to Sql And Entity Framework implementations on &lt;a href="http://kigg.codeplex.com/" target="_blank"&gt;KiGG&lt;/a&gt; as close as possible. I’ve tested it and I guess it is stable enough to be used in production.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://mosesofegypt.net/file.axd?file=EntityFrameworkDataLoadOptionDemo.zip" rel="enclosure" target="_blank"&gt;Sample Download&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You comments and suggestions are appreciated.&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=xg2R9_KKOUY:HTtIPkAKUws:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=xg2R9_KKOUY:HTtIPkAKUws:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?i=xg2R9_KKOUY:HTtIPkAKUws:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=xg2R9_KKOUY:HTtIPkAKUws:7Q72WNTAKBA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=7Q72WNTAKBA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=xg2R9_KKOUY:HTtIPkAKUws:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=xg2R9_KKOUY:HTtIPkAKUws:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?i=xg2R9_KKOUY:HTtIPkAKUws:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/MosesOfEgyptBlog/~4/xg2R9_KKOUY" height="1" width="1"/&gt;</description><dc:publisher xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:publisher><pingback:server xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/pingback.axd</pingback:server><pingback:target xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/post.aspx?id=79250d43-882f-4de3-bae6-92876179dd3d</pingback:target><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">3</slash:comments><trackback:ping xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">http://mosesofegypt.net/trackback.axd?id=79250d43-882f-4de3-bae6-92876179dd3d</trackback:ping><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/post/Introducing-DataLoadOptions-for-Entity-Framework-ObjectContext.aspx#comment</wfw:comment><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/syndication.axd?post=79250d43-882f-4de3-bae6-92876179dd3d</wfw:commentRss><feedburner:origLink>http://mosesofegypt.net/post.aspx?id=79250d43-882f-4de3-bae6-92876179dd3d</feedburner:origLink></item><item><title>What about DataLoadOptions for Entity Framework ObjectContext?</title><link>http://feedproxy.google.com/~r/MosesOfEgyptBlog/~3/ieJydVjccVY/post.aspx</link><category>Entity Framework</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:creator><pubDate>Thu, 23 Apr 2009 18:50:48 PDT</pubDate><guid isPermaLink="false">http://mosesofegypt.net/post.aspx?id=42c27987-da25-4380-8580-90c4374358a1</guid><description>&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/MnSDuxXFehA1w-C5e1zvy_C2Png/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/MnSDuxXFehA1w-C5e1zvy_C2Png/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/MnSDuxXFehA1w-C5e1zvy_C2Png/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/MnSDuxXFehA1w-C5e1zvy_C2Png/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;p&gt;I think the proper way to start this post is to ask How do you do eager loading with &lt;a href="http://msdn.microsoft.com/en-us/library/bb399572.aspx" target="_blank"&gt;Entity Framework&lt;/a&gt;? And the basic native simple answer is by using &lt;em&gt;ObjectQuery&amp;lt;T&amp;gt;.Include(string)&lt;/em&gt; method. No matter what you tried to do, you’ll end up using this way.&lt;/p&gt;  &lt;p&gt;So there was ideas about how enhance the eager loading in our Entity Framework base applications. You can read about some of these ideas:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://msmvps.com/blogs/matthieu/archive/2008/06/06/entityframework-include-with-func.aspx" target="_blank"&gt;Entity Framework Include with Func&lt;/a&gt; &amp;amp; &lt;a href="http://msmvps.com/blogs/matthieu/archive/2008/06/06/entity-framework-include-with-func-next.aspx" rel="tag" target="_blank"&gt;Entity Framework Include with Func next&lt;/a&gt; by &lt;a href="http://msmvps.com/blogs/matthieu/default.aspx" target="_blank"&gt;&lt;strong&gt;Matthieu MEZIL&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://weblogs.asp.net/meligy/archive/2009/04/02/typed-eager-loading-using-entity-framework-amp-what-is-eager-loading-vs-deferred-loading.aspx" rel="tag" target="_blank"&gt;Typed Eager Loading Using Entity Framework (&amp;amp; What is Eager Loading vs Deferred Loading)&lt;/a&gt; by &lt;a href="http://weblogs.asp.net/meligy/default.aspx" target="_blank"&gt;&lt;strong&gt;Meligy&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://www.udidahan.com/2007/04/23/fetching-strategy-design/" rel="tag" target="_blank"&gt;Fetching strategy&lt;/a&gt; posts by &lt;a href="http://www.simonsegal.net/" target="_blank"&gt;&lt;strong&gt;Simon Segal&lt;/strong&gt;&lt;/a&gt;:&lt;/li&gt;    &lt;ul&gt;     &lt;li&gt;&lt;a href="http://www.simonsegal.net/blog/2009/01/07/fetching-strategies-for-the-entity-framework-a-waste-of-time-for-now/" rel="tag" target="_blank"&gt;Fetching Strategies for the Entity Framework - a waste of time for now?&lt;/a&gt;&lt;/li&gt;      &lt;li&gt;&lt;a href="http://www.simonsegal.net/blog/2009/01/13/entity-framework-repository-specifications-and-fetching-strategies/" rel="tag" target="_blank"&gt;Entity Framework Repository, Specifications and Fetching Strategies&lt;/a&gt;&lt;/li&gt;      &lt;li&gt;&lt;a href="http://www.simonsegal.net/blog/2009/02/11/the-entity-framework-and-a-unified-lazy-and-eager-loading-framework/" rel="tag" target="_blank"&gt;The Entity Framework and a unified Lazy and Eager loading framework&lt;/a&gt;&lt;/li&gt;      &lt;li&gt;&lt;a href="http://www.simonsegal.net/blog/2009/02/23/entity-framework-repositories-specifications-and-fetching-strategies-part-90/" rel="tag" target="_blank"&gt;Entity Framework, Repositories, Specifications and Fetching Strategies Part 9.0&lt;/a&gt;&lt;/li&gt;      &lt;li&gt;&lt;a href="http://www.simonsegal.net/blog/2009/02/24/entity-framework-repositories-specifications-and-fetching-strategies-part-100-or-lazy-loading-and-fetching-strategies-again-with-feeling/" rel="tag" target="_blank"&gt;Lazy Loading and Fetching Strategies again, with feeling!&lt;/a&gt;&lt;/li&gt;      &lt;li&gt;&lt;a href="http://www.simonsegal.net/blog/2009/03/05/lazy-loading-and-the-entity-framework-how-long-i-can-go-on-like-this/" rel="tag" target="_blank"&gt;Lazy Loading and the Entity Framework. How long I can go on like this?&lt;/a&gt;&lt;/li&gt;   &lt;/ul&gt; &lt;/ul&gt;  &lt;p&gt;As I said, no matter what you tried, you’ll end up using &lt;em&gt;ObjectQuery&amp;lt;T&amp;gt;.Include(string)&lt;/em&gt;.&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;My Proposal:&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;I am here now to propose my idea. And I am just proposing. What about &lt;a href="http://msdn.microsoft.com/en-us/library/system.data.linq.dataloadoptions.aspx" target="_blank"&gt;DataLoadOptions&lt;/a&gt; for Entity Framework &lt;a href="http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.aspx" target="_blank"&gt;ObjectContext&lt;/a&gt;?! Do You know &lt;a href="http://msdn.microsoft.com/en-us/library/system.data.linq.dataloadoptions.aspx" target="_blank"&gt;DataLoadOptions&lt;/a&gt; class in Linq to Sql?! Yes, I want to steal the idea and make it fit for Entity Framework. I want to implement a tiny clone of &lt;a href="http://msdn.microsoft.com/en-us/library/system.data.linq.dataloadoptions.aspx" target="_blank"&gt;DataLoadOptions&lt;/a&gt; for Entity Framework. This would give you an option similar to this:&lt;/p&gt;  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:99be10cd-6f8b-40ab-922b-f36c2b18f0ee" class="wlWriterEditableSmartContent"&gt;&lt;pre name="code" class="c#:nocontrols"&gt;var context = new NorthwindObjectContext;
var loadOptions = new DataLoadOptions()
DataLoadOptions.LoadWith&amp;lt;Product&amp;gt;(p=&amp;gt;p.Category)
DataLoadOptions.LoadWith&amp;lt;Product&amp;gt;(p=&amp;gt;p.Supplier)

context.LoadOptions = loadOptions;

var products = context.ProductsSet;
&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Of course this is not going to work by itself. The above is a usage sample, however the implementation of such feature will require some coding, and guess what, I’ll end up using &lt;em&gt;ObjectQuery&amp;lt;T&amp;gt;.Include(string)&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Where did I reach?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;I am almost done with this idea! The DataLoadOptions class for EF is completed with tests. It worth to mention that this class is not 100% clone of LINQ to SQL &lt;a href="http://msdn.microsoft.com/en-us/library/system.data.linq.dataloadoptions.aspx" target="_blank"&gt;DataLoadOptions&lt;/a&gt; one! There is a big difference. And I can say for some reason in EF you will not fall in mistakes like cyclic issues (read about it on &lt;a href="http://msdn.microsoft.com/en-us/library/system.data.linq.dataloadoptions.aspx" target="_blank"&gt;DataLoadOptions&lt;/a&gt; remarks section) for example in LINQ to SQL you cannot do this:&lt;/p&gt;

&lt;p&gt;
  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:62156a08-d668-4e75-8505-fc91ac068d21" class="wlWriterEditableSmartContent"&gt;&lt;pre name="code" class="c#:nocontrols"&gt;loadOptions.LoadWith&amp;lt;Product&amp;gt;(p=&amp;gt;p.Category);
loadOptions.LoadWith&amp;lt;Category&amp;gt;(c=&amp;gt;c.Products);&lt;/pre&gt;&lt;/div&gt;
&lt;/p&gt;

&lt;p&gt;But in EF it would be safe because you can control implicitly.&lt;/p&gt;

&lt;p&gt;Conclusion:&lt;/p&gt;

&lt;p&gt;I hope soon I’ll be able to present a demo code. But for now I can say it will be as reusable code that you’ll have to customize to attache to your EF implementation. I am currently integrating it into &lt;a href="http://kigg.codeplex.com/" rel="tag" target="_blank"&gt;KiGG&lt;/a&gt; as part of EF flavour of repository on &lt;a href="http://kigg.codeplex.com/" rel="tag" target="_blank"&gt;KiGG&lt;/a&gt;. At the moment I am writing this post I didn’t comment it to &lt;a href="http://kigg.codeplex.com/SourceControl/ListDownloadableCommits.aspx" target="_blank"&gt;KiGG source control&lt;/a&gt;. So keep tuned.&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=ieJydVjccVY:j-AZKx7Nw6s:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=ieJydVjccVY:j-AZKx7Nw6s:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?i=ieJydVjccVY:j-AZKx7Nw6s:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=ieJydVjccVY:j-AZKx7Nw6s:7Q72WNTAKBA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=7Q72WNTAKBA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=ieJydVjccVY:j-AZKx7Nw6s:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=ieJydVjccVY:j-AZKx7Nw6s:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?i=ieJydVjccVY:j-AZKx7Nw6s:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/MosesOfEgyptBlog/~4/ieJydVjccVY" height="1" width="1"/&gt;</description><dc:publisher xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:publisher><pingback:server xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/pingback.axd</pingback:server><pingback:target xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/post.aspx?id=42c27987-da25-4380-8580-90c4374358a1</pingback:target><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">12</slash:comments><trackback:ping xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">http://mosesofegypt.net/trackback.axd?id=42c27987-da25-4380-8580-90c4374358a1</trackback:ping><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/post/What-about-DataLoadOptions-for-Entity-Framework-ObjectContext.aspx#comment</wfw:comment><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/syndication.axd?post=42c27987-da25-4380-8580-90c4374358a1</wfw:commentRss><feedburner:origLink>http://mosesofegypt.net/post.aspx?id=42c27987-da25-4380-8580-90c4374358a1</feedburner:origLink></item><item><title>Enterprise Library 4.1 Hands-on-Labs</title><link>http://feedproxy.google.com/~r/MosesOfEgyptBlog/~3/wcNG4V0m8lg/post.aspx</link><category>General</category><category>Learning &amp; Certifications</category><category>Bookmark</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:creator><pubDate>Thu, 02 Apr 2009 13:35:34 PDT</pubDate><guid isPermaLink="false">http://mosesofegypt.net/post.aspx?id=587eda62-34c0-48a7-b718-57b8bc8a3ad6</guid><description>&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/AldQoq6TrcaCQnR_pfBePC3JGuk/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/AldQoq6TrcaCQnR_pfBePC3JGuk/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/AldQoq6TrcaCQnR_pfBePC3JGuk/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/AldQoq6TrcaCQnR_pfBePC3JGuk/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;p&gt;Last month (March 2009)&amp;#160; &lt;a href="http://entlib.codeplex.com/Wiki/View.aspx?title=Hands-on Labs" rel="tag" target="_blank"&gt;HOLs for Enterprise Library 4.1 released&lt;/a&gt;. Earlier this year there were HOLs released for &lt;a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=2C34A9CB-17CF-4AEC-8DE6-EEACBBB74413&amp;amp;displaylang=en" rel="tag" target="_blank"&gt;Validation Application Block 4.1&lt;/a&gt;, now a full HOLs is released for the entire Enterprise Library.&lt;/p&gt;  &lt;p&gt;Hands-on Labs walk you through the key usage scenarios of the application blocks in in various application contexts. You can practice the labs from start to finish or you can use the starter solutions provided to complete only the labs you want to, in the order you prefer.&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://www.microsoft.com/downloads/details.aspx?displaylang=en&amp;amp;FamilyID=ab3f2168-fea1-4fc2-b40c-7867d99d4b6a"&gt;Enterprise Library for .NET Framework 3.5 (v4.1) Hands On Labs&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://www.microsoft.com/downloads/details.aspx?displaylang=en&amp;amp;FamilyID=93a5e18f-3211-44ef-b785-c59bcec4cd6f"&gt;Unity Application Block (1.2) Hands On Labs&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=2C34A9CB-17CF-4AEC-8DE6-EEACBBB74413&amp;amp;displaylang=en"&gt;Validation Application Block (4.1) Hands On Labs&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=wcNG4V0m8lg:ClYkvSgpDr8:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=wcNG4V0m8lg:ClYkvSgpDr8:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?i=wcNG4V0m8lg:ClYkvSgpDr8:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=wcNG4V0m8lg:ClYkvSgpDr8:7Q72WNTAKBA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=7Q72WNTAKBA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=wcNG4V0m8lg:ClYkvSgpDr8:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=wcNG4V0m8lg:ClYkvSgpDr8:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?i=wcNG4V0m8lg:ClYkvSgpDr8:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/MosesOfEgyptBlog/~4/wcNG4V0m8lg" height="1" width="1"/&gt;</description><dc:publisher xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:publisher><pingback:server xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/pingback.axd</pingback:server><pingback:target xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/post.aspx?id=587eda62-34c0-48a7-b718-57b8bc8a3ad6</pingback:target><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">1</slash:comments><trackback:ping xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">http://mosesofegypt.net/trackback.axd?id=587eda62-34c0-48a7-b718-57b8bc8a3ad6</trackback:ping><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/post/EntLib41HOLsReleased.aspx#comment</wfw:comment><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/syndication.axd?post=587eda62-34c0-48a7-b718-57b8bc8a3ad6</wfw:commentRss><feedburner:origLink>http://mosesofegypt.net/post.aspx?id=587eda62-34c0-48a7-b718-57b8bc8a3ad6</feedburner:origLink></item><item><title>Domain Driven Design &amp; Test Driven Development\Design using Entity Framework, Part 2.A Unit Testing Entities With Moq 3</title><link>http://feedproxy.google.com/~r/MosesOfEgyptBlog/~3/HiATUZKmSM0/post.aspx</link><category>Entity Framework</category><category>LINQ</category><category>Software Design</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:creator><pubDate>Tue, 24 Mar 2009 13:10:36 PDT</pubDate><guid isPermaLink="false">http://mosesofegypt.net/post.aspx?id=a8dd8f82-e232-4d33-839b-58cf53bddce7</guid><description>&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/ogPPk0PYnHGKyjoH7gz8ccM8tEY/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/ogPPk0PYnHGKyjoH7gz8ccM8tEY/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/ogPPk0PYnHGKyjoH7gz8ccM8tEY/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/ogPPk0PYnHGKyjoH7gz8ccM8tEY/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;p&gt;I had &lt;a href="http://mosesofegypt.net/post/TDDandTDDWithEFPart1BuildingDomainObjectModel.aspx" rel="tag" target="_blank"&gt;few&lt;/a&gt; &lt;a href="http://mosesofegypt.net/post/DDD-And-TDD-with-EF-Part1A-Refactoring-And-Unit-Testing.aspx" rel="tag" target="_blank"&gt;previous&lt;/a&gt; &lt;a href="http://mosesofegypt.net/post/DDDandTDDwithEFPart1bReview.aspx" rel="tag" target="_blank"&gt;posts&lt;/a&gt; about DDD &amp;amp; TDD with Entity Framework that you might need to return to them before you proceed with this post. To summarize these posts, I was trying to build testable Models that is based on EF. But EF doesn't support Persistence Ignorance in its first version which make testing it in most cases require a database connection where you can test you code against it. My target was to build a testable models based on EF and that is independent of any underlying data source.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Introduction, Domain Model Review:&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://mosesofegypt.net/image.axd?picture=WindowsLiveWriter/DomainDrivenDesignTestDrivenDevelopmentD_582/EntityModel-DDD_2.jpg" rel="lightbox"&gt;&lt;img style="border-right-width: 0px; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" border="0" alt="EntityModel-DDD" src="http://mosesofegypt.net/image.axd?picture=WindowsLiveWriter/DomainDrivenDesignTestDrivenDevelopmentD_582/EntityModel-DDD_3.jpg" width="604" height="375" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://mosesofegypt.net/image.axd?picture=WindowsLiveWriter/DomainDrivenDesignTestDrivenDevelopmentD_582/Northwind_2.png" rel="lightbox"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Northwind" border="0" alt="Northwind" src="http://mosesofegypt.net/image.axd?picture=WindowsLiveWriter/DomainDrivenDesignTestDrivenDevelopmentD_582/Northwind_3.png" width="604" height="529" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;The above image shows class diagram of my northwind domain model. It is a set of interfaces where I define data contracts of each entity. It is very simple, but there is one thing I want to highlight in this model. It is the &lt;em&gt;IEntityCollection&lt;/em&gt; generic interface. Actually this is an empty interface that is considered a combination of &lt;em&gt;ICollection&amp;lt;T&amp;gt;&lt;/em&gt;, &lt;em&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/em&gt;, &lt;em&gt;IEnumerable&lt;/em&gt; and &lt;em&gt;IListSource&lt;/em&gt;. This interface defines a collection of related entities such as the case &lt;em&gt;ICategory&lt;/em&gt; that should contains a collection of &lt;em&gt;IProduct&lt;/em&gt;.&lt;/p&gt;  &lt;p&gt;So &lt;em&gt;ICategory&lt;/em&gt; should contain an &lt;em&gt;IEntityCollection&lt;/em&gt; of products &lt;em&gt;IEntityCollection&amp;lt;IProduct&amp;gt;&lt;/em&gt;. Same thing for &lt;em&gt;ISupplier&lt;/em&gt;. And for &lt;em&gt;IProduct&lt;/em&gt; it should contain a navigation property for both &lt;em&gt;ISupplier&lt;/em&gt; and &lt;em&gt;ICategory&lt;/em&gt;.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Issue with EF generated entities:&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;EF generated entities cannot be tested without physical connection to data source. For example generated entities cannot be mocked because it will require a physical data source.&amp;#160; But interfaces can be mocked. And because we have entities that implements those interfaces, then we need to test these entities.&lt;/p&gt;  &lt;p&gt;Regardless of mocking, you'll also face troubles when you work with real entities specially when you try to access navigation properties or collections. Especially if the collection are lazy loading ones. Then you will need to call Load which will require to hit the data store to retrieve related collection of data.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;What Exactly I need to test in entities?&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Basically I need to test navigation properties both scalar and collection ones. Navigation properties in EF depends on &lt;em&gt;EntityReference&amp;lt;T&amp;gt;&lt;/em&gt; and &lt;em&gt;EntityCollection&amp;lt;T&amp;gt;&lt;/em&gt; classes. Both are sealed classes, also these generated properties such as &lt;em&gt;EntityCollection&lt;/em&gt; of products will require to hit data store. So I cannot mocke instance of those classes.&lt;/p&gt;  &lt;p&gt;For example I need to test &lt;em&gt;Category.Products&lt;/em&gt; that it loads data if not already loaded. This is what I want to test and without connecting to data store. Same thing for &lt;em&gt;Product.Category&lt;/em&gt;&amp;#160; which will require the &lt;em&gt;EntityReference&amp;lt;Category&amp;gt;&lt;/em&gt; to be loaded in order to &lt;em&gt;Category&lt;/em&gt; property of &lt;em&gt;Product&lt;/em&gt; class to return a result.&lt;/p&gt;  &lt;p&gt;So I will need to mock &lt;em&gt;EntityReference&amp;lt;T&amp;gt;&lt;/em&gt; properties and &lt;em&gt;EntityCollection&amp;lt;T&amp;gt;&lt;/em&gt; properties. And as I mentioned above they cannot be mocked because they are sealed. So my solution was to build a wrapper for both classes in order to be able to mock them.&lt;/p&gt;  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:7a2a57e4-41ae-43bd-a331-c3ace50f059a" class="wlWriterEditableSmartContent"&gt;&lt;pre name="code" class="c#:nocontrols"&gt;public class EntityReferenceWrapper&amp;lt;TEntity&amp;gt; 
	where TEntity : class, IEntityWithRelationships, IEntity
{
    EntityReference&amp;lt;TEntity&amp;gt; _entityReference;
    public EntityReferenceWrapper(EntityReference&amp;lt;TEntity&amp;gt; entityReference)
    {
        _entityReference = entityReference;
    }
    
    [SoapIgnore]
    [XmlIgnore]
    public virtual TEntity Value 
    { 
        get { return _entityReference.Value; } 
        set { _entityReference.Value = value; } 
    }

    public void Attach(TEntity entity)
    {
        _entityReference.Attach(entity);
    }

    public ObjectQuery&amp;lt;TEntity&amp;gt; CreateSourceQuery()
    {
        return _entityReference.CreateSourceQuery();
    }

    public virtual void Load()
    {
        _entityReference.Load();
    }

    public virtual bool IsLoaded
    {
        get
        {
            return _entityReference.IsLoaded;
        }
    }
}

public class EntityCollectionWrapper&amp;lt;TInterface, TEntity&amp;gt; : IEntityCollection&amp;lt;TInterface&amp;gt;
    where TInterface : class, IEntity
    where TEntity : class, IEntityWithRelationships, TInterface
{
    private readonly EntityCollection&amp;lt;TEntity&amp;gt; _entityCollection;
    public EntityCollectionWrapper(EntityCollection&amp;lt;TEntity&amp;gt; entityCollection)
    {
        _entityCollection = entityCollection;
    }

    public int Count { get { return _entityCollection.Count; } }
    public bool IsReadOnly { get { return _entityCollection.IsReadOnly;} }
    public virtual bool IsLoaded
    {
        get { return _entityCollection.IsLoaded; }
    }
    public virtual void Load()
    {
        _entityCollection.Load();
    }
    public virtual IQueryable&amp;lt;TEntity&amp;gt; CreateSourceQuery()
    {
        return _entityCollection.CreateSourceQuery();
    }
    public bool Contains(TInterface entity)
    {
        return _entityCollection.Contains(entity as TEntity);
    }
    public void Add(TInterface entity)
    {
        _entityCollection.Add(entity as TEntity);
    }
    public bool Remove(TInterface entity)
    {
        return _entityCollection.Remove(entity as TEntity);
    }
    public void Clear()
    {
        _entityCollection.Clear();
    }
    public void CopyTo(TInterface[] array, int arrayIndex)
    {
        TEntity[] entitiesArray = null;
        _entityCollection.CopyTo(entitiesArray, arrayIndex);
        array = entitiesArray.Cast&amp;lt;TInterface&amp;gt;().ToArray();
    }
    public IEnumerator&amp;lt;TInterface&amp;gt; GetEnumerator()
    {
        return _entityCollection.Cast&amp;lt;TInterface&amp;gt;().GetEnumerator();
    }
	//IListSource &amp;amp; IEnumerator implementation were omitted for code clearance
}
&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Unit Tests for Entities:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Each of &lt;em&gt;ICategory&lt;/em&gt; and &lt;em&gt;ISupplier&lt;/em&gt; contains &lt;em&gt;IEntityCollection&amp;lt;Product&amp;gt;&lt;/em&gt; property called &lt;em&gt;Products&lt;/em&gt;. While &lt;em&gt;IProduct&lt;/em&gt; has 2 navigation properties for &lt;em&gt;ICategory&lt;/em&gt; (&lt;em&gt;Category&lt;/em&gt; property) and &lt;em&gt;ISupplier&lt;/em&gt; (&lt;em&gt;Supplier&lt;/em&gt; property).&lt;/p&gt;

&lt;p&gt;For &lt;em&gt;ICategory&lt;/em&gt; or &lt;em&gt;ISupplier&lt;/em&gt; implementations which would be generated and modified entities &lt;em&gt;Category&lt;/em&gt; and &lt;em&gt;Supplier&lt;/em&gt; classes, I want to test the following:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;when calling Products property is should class &lt;em&gt;EntityCollectionWrapper.&lt;/em&gt;&lt;em&gt;Load&lt;/em&gt; method if the products is not already loaded –&lt;em&gt;IsLoaded&lt;/em&gt; is false- this should simulate calling to original &lt;em&gt;EntityCollection&amp;lt;TEntity&amp;gt;.Load&lt;/em&gt; method. &lt;/li&gt;

  &lt;li&gt;When calling ProductCount method, this should trigger &lt;em&gt;EntityCollectionWrapper.CreateSourceQuery &lt;/em&gt;method which should simulate calling to original &lt;em&gt;EntityCollection&amp;lt;TEntity&amp;gt;.CreateSourceQuery &lt;/em&gt;method. &lt;/li&gt;

  &lt;li&gt;When calling &lt;em&gt;Add&lt;/em&gt; method of &lt;em&gt;Products&lt;/em&gt; property (e.g. &lt;em&gt;category.Products.Add(product)&lt;/em&gt;) this should increase Products collection count. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;Below is the declaration of &lt;em&gt;CategoryTest&lt;/em&gt; Class:&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:ef0edca0-cc14-4b3b-bd53-f6439ec887e0" class="wlWriterEditableSmartContent"&gt;&lt;pre name="code" class="c#:nocontrols"&gt;[TestClass]
public class CategoryTest
{
	private readonly Category _category;
	private readonly Mock&amp;lt;EntityCollectionWrapper&amp;lt;IProduct, Product&amp;gt;&amp;gt;  _mockedProducts;
	public CategoryTest()
	{
		_category = new Category();
		_mockedProducts = new Mock&amp;lt;EntityCollectionWrapper&amp;lt;IProduct, Product&amp;gt;&amp;gt;(_category.ProductsInternal);
	}
	//Rest of code omitted and will be discussed later
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;As you notice in the above code line 5, there is a mocked object of EntityCollectionWrapper class that is instantiated in the constructor line 9. But how exactly I am going to set the related field in Category class? Below are the &lt;em&gt;Category&lt;/em&gt; class implementation for &lt;em&gt;ICategory&lt;/em&gt; interface:&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:66da898b-1409-4ba8-bbd0-80232b3b856c" class="wlWriterEditableSmartContent"&gt;&lt;pre name="code" class="c#:nocontrols"&gt;public partial class Category : ICategory
{
    private EntityCollectionWrapper&amp;lt;IProduct,Product&amp;gt; _products;

    public IEntityCollection&amp;lt;IProduct&amp;gt; Products
    {
        get 
        {
            EnsureProducts();
            if (!_products.IsLoaded)
            {
                _products.Load();
            }
            return _products;
        }
    }

    public int ProductCount
    {
        get
        {
            EnsureProducts();
            return _products.CreateSourceQuery().Count();
        }
    }

    private void EnsureProducts()
    {
        if (_products == null)
        {
            _products = new EntityCollectionWrapper&amp;lt;IProduct, Product&amp;gt;(this.ProductsInternal);
        }
    }

    /// &amp;lt;summary&amp;gt;
    /// Helper method used for unit testing purpose only to set Mocked EntityCollectionWrapper
    /// to local private object _products.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name="mockedProducts"&amp;gt;Mock object of EntityCollectionWrapper&amp;lt;/param&amp;gt;
    internal void SetMockedEntityCollection(EntityCollectionWrapper&amp;lt;IProduct,Product&amp;gt; mockedProducts)
    {
        _products = mockedProducts;
    }
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;Last method on line 40 is internal method that is used only for testing purpose to assign a mocked instance of &lt;em&gt;EntityCollectionWrapper&lt;/em&gt; to the local private member of the same type.&lt;/p&gt;

&lt;p&gt;Also It worth to mention that the generated &lt;em&gt;EntityCollection&amp;lt;Product&amp;gt;&lt;/em&gt; property which called here &lt;em&gt;ProductsInternal&lt;/em&gt; has internal access modifier, because this is also is being used internally as well as from the testing project.&lt;/p&gt;

&lt;p&gt;Now back to &lt;em&gt;CategoryTest&lt;/em&gt; class, I am using the following method as my test initialization method:&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:d1bf9fb1-7026-48fe-b062-5b41789df1b5" class="wlWriterEditableSmartContent"&gt;&lt;pre name="code" class="c#:nocontrols"&gt;[TestInitialize]
public void TestInitialize()
{
	_category.SetMockedEntityCollection(_mockedProducts.Object);
}&lt;/pre&gt;&lt;/div&gt;

&lt;br /&gt;Simply it makes a call to the internal method &lt;em&gt;SetMockedEntityCollection&lt;/em&gt; and pass the mocked object as parameter to it. Now that I have a mocked object injected into my class I can start setup my results to continue testing. 

&lt;p&gt;&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:f3aa71f9-f9cb-45bf-8a1b-7479e8435308" class="wlWriterEditableSmartContent"&gt;&lt;pre name="code" class="c#:nocontrols"&gt;[TestMethod]
public void Category_Products_Should_Call_EntityCollection_Load_If_ProductsInternal_Not_Loaded()
{
    _mockedProducts.SetupGet(p =&amp;gt; p.IsLoaded).Returns(false).Verifiable();
    _mockedProducts.Setup(p =&amp;gt; p.Load()).Verifiable();
    IEntityCollection&amp;lt;IProduct&amp;gt; products = _category.Products;

    _mockedProducts.Verify();
}&lt;/pre&gt;&lt;/div&gt;

&lt;br /&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;In the above code I am testing lazy loading. If the collection is not loaded &lt;em&gt;Load&lt;/em&gt; method of the &lt;em&gt;EntityCollection&lt;/em&gt; should be called. At line 4 I set assumption that &lt;em&gt;EntityCollectionWrapper&amp;lt;IProduct,Product&amp;gt;.IsLoaded&lt;/em&gt; should return false. And as this property must be called I’m asking to verify that it will be called using &lt;em&gt;Verifiable&lt;/em&gt; method. At line 5 I am asking to verify that &lt;em&gt;Load&lt;/em&gt; method is being called. Finally line 8 when calling &lt;em&gt;Verify&lt;/em&gt; method, all verifiable calls will be evaluated and if one of the verifiable calls never occur and exception will be thrown and the test method will fail.&lt;/p&gt;

&lt;p&gt;The other 2 tests that I motioned earlier are below:&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:2218aca4-22ad-4e6c-be48-4c9fb47cf2a0" class="wlWriterEditableSmartContent"&gt;&lt;pre name="code" class="c#:nocontrols"&gt;[TestMethod]
public void Category_ProductCount_Should_Call_EntityCollection_CreateSourceQuery()
{
    IList&amp;lt;Product&amp;gt; products = new List&amp;lt;Product&amp;gt;();
    _mockedProducts.Setup(p =&amp;gt; p.CreateSourceQuery()).Returns(products.AsQueryable()).Verifiable();
    
    int count = _category.ProductCount;

    _mockedProducts.Verify();
}

[TestMethod]
public void Category_Add_Product_To_Products_Collection_Should_Increase_Collection_Count()
{
    _category.Products.Add(new Product());
    Assert.AreEqual(1, _category.Products.Count);
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;I think I delivered my idea here. So you can explore the &lt;a href="http://mosesofegypt.net/file.axd?file=TDDWithEFSamplePart2A.zip" rel="enclosure" target="_blank"&gt;attached solution&lt;/a&gt; for the rest of unit tests of both entities &lt;em&gt;Product&lt;/em&gt; and &lt;em&gt;Supplier&lt;/em&gt;. &lt;em&gt;Supplier&lt;/em&gt; is exactly the same as &lt;em&gt;Category&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;I next post I will provide code for integration testing this. Just to make sure that this is really going to work with &lt;a href="http://msdn.microsoft.com/en-us/library/bb399572.aspx" target="_blank"&gt;Entity Framework&lt;/a&gt;. For the time being, trust me it does work.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://mosesofegypt.net/file.axd?file=TDDWithEFSamplePart2A.zip" rel="enclosure"&gt;Download Sample Project&lt;/a&gt;.&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=HiATUZKmSM0:OtPeR10Ab7k:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=HiATUZKmSM0:OtPeR10Ab7k:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?i=HiATUZKmSM0:OtPeR10Ab7k:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=HiATUZKmSM0:OtPeR10Ab7k:7Q72WNTAKBA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=7Q72WNTAKBA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=HiATUZKmSM0:OtPeR10Ab7k:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=HiATUZKmSM0:OtPeR10Ab7k:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?i=HiATUZKmSM0:OtPeR10Ab7k:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/MosesOfEgyptBlog/~4/HiATUZKmSM0" height="1" width="1"/&gt;</description><dc:publisher xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:publisher><pingback:server xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/pingback.axd</pingback:server><pingback:target xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/post.aspx?id=a8dd8f82-e232-4d33-839b-58cf53bddce7</pingback:target><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">5</slash:comments><trackback:ping xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">http://mosesofegypt.net/trackback.axd?id=a8dd8f82-e232-4d33-839b-58cf53bddce7</trackback:ping><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/post/DDDandTDDUsingEFPart2AUnitTestingEntitiesWithMoq3.aspx#comment</wfw:comment><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/syndication.axd?post=a8dd8f82-e232-4d33-839b-58cf53bddce7</wfw:commentRss><feedburner:origLink>http://mosesofegypt.net/post.aspx?id=a8dd8f82-e232-4d33-839b-58cf53bddce7</feedburner:origLink></item><item><title>Book Review: ASP.NET 3.5 Application Architecture and Design</title><link>http://feedproxy.google.com/~r/MosesOfEgyptBlog/~3/ie31EmQ10CM/post.aspx</link><category>ASP.NET</category><category>General</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:creator><pubDate>Sat, 14 Mar 2009 13:46:50 PDT</pubDate><guid isPermaLink="false">http://mosesofegypt.net/post.aspx?id=e3d65908-ffad-43d7-af75-ad91dce62bad</guid><description>&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/nZBX5f9Sm7p-Kezsaju1-SV_9EE/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/nZBX5f9Sm7p-Kezsaju1-SV_9EE/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/nZBX5f9Sm7p-Kezsaju1-SV_9EE/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/nZBX5f9Sm7p-Kezsaju1-SV_9EE/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Information about the book:&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Book Title:&lt;/strong&gt; &lt;a href="http://www.packtpub.com/application-architecture-and-design-for-asp-.net-3.5/book/mid/090109cg9gas" target="_blank"&gt;ASP.NET 3.5 Application Architecture and Design&lt;/a&gt;     &lt;br /&gt;&lt;strong&gt;Book's Page:&lt;/strong&gt; &lt;a title="http://www.packtpub.com/application-architecture-and-design-for-asp-.net-3.5/book" href="http://www.packtpub.com/application-architecture-and-design-for-asp-.net-3.5/book"&gt;http://www.packtpub.com/application-architecture-and-design-for-asp-.net-3.5/book&lt;/a&gt;     &lt;br /&gt;&lt;strong&gt;Book Cover&lt;/strong&gt;     &lt;br /&gt;&lt;a title="ASP.NET 3.5 Application Architecture and Design" href="http://www.packtpub.com/application-architecture-and-design-for-asp-.net-3.5/book/mid/090109cg9gas" target="_blank"&gt;&lt;img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="244" alt="ASP.NET3.5ApplicationArchitectureandDesign" src="http://mosesofegypt.net/image.axd?picture=WindowsLiveWriter/BookRe.5ApplicationArchitectureandDesign_11FE9/ASP.NET3.5ApplicationArchitectureandDesign_3.jpg" width="199" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Chapters:&lt;/strong&gt; 9     &lt;br /&gt;&lt;strong&gt;Publisher:&lt;/strong&gt; &lt;a href="http://www.packtpub.com/"&gt;PACKT Publishing&lt;/a&gt;     &lt;br /&gt;&lt;strong&gt;Author:&lt;/strong&gt; &lt;a href="http://www.packtpub.com/author_view_profile/id/250" target="_blank"&gt;Vivek Thakur&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Introduction:&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Microsoft ASP.NET has quickly evolved to become one of the most famous platforms for developing web-based solutions. Since its first release with .Net 1.0, Microsoft has continuously added many out-of-the-box features and components, making web development easier for the end developer. As ASP.NET is part of the whole .Net Framework, it is gaining benefits of all features and technologies provided by the .Net Framework itself. With the introduction of LINQ, MS AJAX, WCF, WPF, and a lot of exciting new tools, the .NET framework has not only grown large but also flexible, in terms of the choices and options being offered to the developers.&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;About ASP.NET 3.5 Application Architecture and Design Book:&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://www.packtpub.com/application-architecture-and-design-for-asp-.net-3.5/book" target="_blank"&gt;ASP.NET 3.5 Application Architecture and Design&lt;/a&gt; book is a small one (239) pages divided into 9 chapters. It is not a &amp;quot;pure&amp;quot; architecture and design guide. Rather, the goal is to show you how to design a web site in ASP.NET the correct way, focus on different design options, analyze and study what architectural options we have, and decide when to use which    &lt;br /&gt;architectural solution.&lt;/p&gt;  &lt;p&gt;Although this book primarily aimed at beginner and intermediate developers, it is a good resource for experienced programmers as well. This book is not a theoretical guide on architecture and design patterns, or any other technology.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;ASP.NET 3.5 Application Architecture and Design at glance:&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;The book contains 9 chapters as the following:&lt;/p&gt;  &lt;p&gt;&lt;em&gt;Chapter 1 Introduction to Architecture and Design&lt;/em&gt;. This chapter focus on Understanding architecture and design from a practical point of view as well as architectural styles. It talks about what design patterns are, what are different stages for a project lifecycle and what is the difference between tiers and layers.&lt;/p&gt;  &lt;p&gt;&lt;em&gt;Chapter 2 1-Tier 1-Layer Architecture in ASP.NET&lt;/em&gt;. Start diving into ASP.NET code, this chapter shows through the use of examples the default N-Tier nature of web applications, why applications based on classic inline ASP are tightly coupled and What 1-tier 1-layer architecture is? It show how to use code-behind classes in ASP.NET as another layer in the UI tier and how Data Source Controls fit into the application architecture of ASP.NET web applications. However this chapter is not a guide on how to use Data Source controls. This chapter also shows how the 1-tier, 1-layer style is tightly-coupled and is not flexible or scalable.&lt;/p&gt;  &lt;p&gt;&lt;em&gt;Chapter 3 ER Diagrams, Domain Model, and N-Layer Architecture&lt;/em&gt;. After learning and seeing the basic layering of the monolithic 1-tier 1-layer architectural style in action in chapter 2 and understanding that this 1-tier 1-layer architecture is the default style in ASP.NET and Visual Studio 2005/2008. This chapter talks about how to overcome the limitation of this style by further break the application code into n-layers. This chapter will teach you the 2 layer style, understanding ER diagrams, what domain model is and what are UML relationships and basics of UML. It will go through 3 layer style and discuss the drawbacks or limitations of this model. It will also talks about object data source control and where it will fit in your application design.&lt;/p&gt;  &lt;p&gt;&lt;em&gt;Chapter 4 N-Tier Architecture&lt;/em&gt;. Talks about n-tier architecture in ASP.NET, why it is needed and how to implement it. It also explains Data Transfer Objects and how to use them with 4-tier and 5-tier web solutions.&lt;/p&gt;  &lt;p&gt;&lt;em&gt;Chapter 5 Model View Controller&lt;/em&gt;. The brand new feature in ASP.NET, the ASP.NET MVC. You will learn and understand what MVC design is, and how the ASP.NET MVC framework will help you quickly implement MVC design in your web applications. Through this chapter, you'll understand the basic ASP.NET web forms Page Controller Pattern and why MVC pattern is needed.&lt;/p&gt;  &lt;p&gt;&lt;em&gt;Chapter 6 Design Patterns&lt;/em&gt;. As you go through the previous chapters, you'll learn about different types of design patters. In this chapter you will learn how and when to use the most common design patterns in ASP.NET such as Factory, Dependency Injection, Singleton, and others with examples.&lt;/p&gt;  &lt;p&gt;&lt;em&gt;Chapter 7 SOA and WCF&lt;/em&gt;. This chapter discuss what is SOA (Service oriented architecture) and why it is need, explaining the advantages of SOA for a beginner. You'll learn about SOA and web services. And then you'll learn what WCF and how to implement SOA using WCF.&lt;/p&gt;  &lt;p&gt;&lt;em&gt;Chapter 8 Database Design&lt;/em&gt;. You'll learn how much a well designed database is important. You'll learn about logical &amp;amp; physical models, what is data integrity and how to make your database designed normalized.&lt;/p&gt;  &lt;p&gt;&lt;em&gt;Chapter 9 Localization&lt;/em&gt;. One of the important subjects about building web application is how to localize your application. This chapter discuss what is localization and globalizations, and what are the best practices to follow while implementing globalization. Bow to build localizable ASP.NET 3.5 web application using features of ASP.NET.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Personal Opinion:&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;The book is a great resource for beginners and intermediate ASP.NET developers. Personally I met many web developers (ASP.NET) who know nothing about basic web application architecture &amp;amp; design and design patterns. I wished that there is a single crash start resource where they can learn the solid basic about this subject. I can say I finally found this resource, it is the ASP.NET 3.5 Application Architecture and Design book. Very well organized and take your through the basics step by step till you fully understand the difference between each style and where each style might fit.&lt;/p&gt;  &lt;p&gt;May rate for this book is &lt;strong&gt;4&lt;/strong&gt; out of 5.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Conclusion:&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;My recommendation for beginners ASP.NET web developers is to read this book, especially if they have no practical experience. This book is not ASP.NET How to! It is about the basics of how to architect and design ASP.NET 3.5 web based application, and what are the options available for that as well as the options provided by .Net Framework and VS.NET out of the box to ease this job.&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=ie31EmQ10CM:rWh58MdH2bM:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=ie31EmQ10CM:rWh58MdH2bM:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?i=ie31EmQ10CM:rWh58MdH2bM:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=ie31EmQ10CM:rWh58MdH2bM:7Q72WNTAKBA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=7Q72WNTAKBA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=ie31EmQ10CM:rWh58MdH2bM:dnMXMwOfBR0"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?d=dnMXMwOfBR0" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?a=ie31EmQ10CM:rWh58MdH2bM:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/MosesOfEgyptBlog?i=ie31EmQ10CM:rWh58MdH2bM:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/MosesOfEgyptBlog/~4/ie31EmQ10CM" height="1" width="1"/&gt;</description><dc:publisher xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:publisher><pingback:server xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/pingback.axd</pingback:server><pingback:target xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/post.aspx?id=e3d65908-ffad-43d7-af75-ad91dce62bad</pingback:target><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">5</slash:comments><trackback:ping xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">http://mosesofegypt.net/trackback.axd?id=e3d65908-ffad-43d7-af75-ad91dce62bad</trackback:ping><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/post/BookReviewASPNET35ApplicationArchitectureandDesign.aspx#comment</wfw:comment><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/syndication.axd?post=e3d65908-ffad-43d7-af75-ad91dce62bad</wfw:commentRss><feedburner:origLink>http://mosesofegypt.net/post.aspx?id=e3d65908-ffad-43d7-af75-ad91dce62bad</feedburner:origLink></item><item><title>Domain Driven Design &amp; Test Driven Design\Development with Entity Framework Part 1.b Integration Testing for ObjectContext</title><link>http://feedproxy.google.com/~r/MosesOfEgyptBlog/~3/9p0rr12RiU8/post.aspx</link><category>Entity Framework</category><category>LINQ</category><category>Software Design</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:creator><pubDate>Mon, 23 Feb 2009 00:00:26 PST</pubDate><guid isPermaLink="false">http://mosesofegypt.net/post.aspx?id=17933ccd-8c75-4cdc-ae40-9b9c0083e9e7</guid><description>&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/YWjHyf3fqqbboYsNyq5VCWfPVLc/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/YWjHyf3fqqbboYsNyq5VCWfPVLc/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/YWjHyf3fqqbboYsNyq5VCWfPVLc/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/YWjHyf3fqqbboYsNyq5VCWfPVLc/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;p&gt;I decided to provide some integration testing before proceeding as a proof of concept. In integration testing I will connect to the database and perform unit testing while connecting to the database.\&lt;/p&gt;  &lt;p&gt;This unit test is almost identical to the one in my previous post. Except here I am testing the results that is coming out from EF and Database.&lt;/p&gt;  &lt;p&gt;My target is to test &lt;em&gt;IDataContext&lt;/em&gt; Implemented methods in &lt;em&gt;NorthwindDataContext&lt;/em&gt;. Find below the Integration unit testing class. &lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;div class="wlWriterSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:892bb4db-0dc4-4c98-9290-5495d2f2f009" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;pre name="code" class="c#:nocontrols"&gt;[TestClass]
public class NorthwindDataContextIntegrationTest : IDisposable
{
    IDataContext _context;
    public NorthwindDataContextIntegrationTest()
    {
        _context = new NorthwindDataContext(ConfigurationManager
                    .ConnectionStrings["NorthwindDatabaseContext"]
                    .ConnectionString);
    }
    
    [TestMethod]
    public void NorthwindDataContext_CategoryDataSource_Returns_CategorySet()
    {
        Assert.IsNotNull(_context.CategoryDataSource);
    }
    
    [TestMethod]
    public void NorthwindDataContext_ProductDataSource_Returns_ProductSet()
    {
        Assert.IsNotNull(_context.ProductDataSource);
    }

    [TestMethod]
    public void NorthwindDataContext_SupplierDataSource_Returns_SupplierSet()
    {
        Assert.IsNotNull(_context.SupplierDataSource);
    }
    
    [TestMethod]
    public void NorthwindDataContext_Insert_Should_Change_Instance_EntityState_To_Added()
    {
        var category = Category.CreateCategory(1, "New Category");
        
        _context.InsertOnSubmit("CategorySet",category);

        Assert.AreEqual(category.EntityState, System.Data.EntityState.Added);
    }

    [TestMethod]
    public void NorthwindDataContext_Delete_Should_Change_Instance_EntityState_To_Deleted()
    {
        var category = _context.CategoryDataSource.FirstOrDefault();
        
        _context.DeleteOnSubmit(category);

        Assert.AreEqual(category.EntityState, System.Data.EntityState.Deleted);
    }
    
    public void Dispose()
    {
        ((NorthwindDataContext)_context).Dispose();
    }
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="ttp://mosesofegypt.net/file.axd?file=TDDWithEFSampleModified.zip" target="_blank" rel="enclosure"&gt;Download Source Code&lt;/a&gt;.&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?a=1VV7kpAu"&gt;&lt;img src="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?d=41" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?a=7GEVbesr"&gt;&lt;img src="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?i=7GEVbesr" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?a=haHIViMo"&gt;&lt;img src="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?d=50" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?a=DYiixpwo"&gt;&lt;img src="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?d=43" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?a=Lnvb8SUf"&gt;&lt;img src="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?i=Lnvb8SUf" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/MosesOfEgyptBlog/~4/9p0rr12RiU8" height="1" width="1"/&gt;</description><dc:publisher xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:publisher><pingback:server xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/pingback.axd</pingback:server><pingback:target xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/post.aspx?id=17933ccd-8c75-4cdc-ae40-9b9c0083e9e7</pingback:target><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">2</slash:comments><trackback:ping xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">http://mosesofegypt.net/trackback.axd?id=17933ccd-8c75-4cdc-ae40-9b9c0083e9e7</trackback:ping><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/post/DDDandTDDwithEFPart1bIntegrationUnitTestingforObjectContext.aspx#comment</wfw:comment><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/syndication.axd?post=17933ccd-8c75-4cdc-ae40-9b9c0083e9e7</wfw:commentRss><feedburner:origLink>http://mosesofegypt.net/post.aspx?id=17933ccd-8c75-4cdc-ae40-9b9c0083e9e7</feedburner:origLink></item><item><title>Domain Driven Design &amp; Test Driven Development\Design with Entity Framework Part 1.b, Review</title><link>http://feedproxy.google.com/~r/MosesOfEgyptBlog/~3/LAgkhgRsz0I/post.aspx</link><category>Entity Framework</category><category>LINQ</category><category>Software Design</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:creator><pubDate>Sat, 21 Feb 2009 10:43:18 PST</pubDate><guid isPermaLink="false">http://mosesofegypt.net/post.aspx?id=325c0305-01a3-4f66-8996-fb1c0c4dc2da</guid><description>&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/m7aHb8p5tbwvjbL-ZRVB1F9U-ds/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/m7aHb8p5tbwvjbL-ZRVB1F9U-ds/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/m7aHb8p5tbwvjbL-ZRVB1F9U-ds/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/m7aHb8p5tbwvjbL-ZRVB1F9U-ds/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;p&gt;In return to my previous posts about DDD &amp;amp; TDD with EF. I discovered few catches in my design that I wished to high light and discuss in this post. To summarize my take here are the head lines:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;What is the Responsibility of ObjectContext in EF?&lt;/li&gt;    &lt;li&gt;What is the Responsibilities of Repositories and whether they should be coupled with EF or not?&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;I come up with this post after few discussions through e-mail with &lt;a href="http://landman-code.blogspot.com/" target="_blank"&gt;Davy Landman&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Responsibility of ObjectContext:&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;After reviewing my code and in &lt;a href="http://mosesofegypt.net/post/DDD-And-TDD-with-EF-Part1A-Refactoring-And-Unit-Testing.aspx" target="_blank" rel="tag"&gt;previous post&lt;/a&gt;, I found that I am giving too much responsibilities to &lt;em&gt;ObjectContext&lt;/em&gt;. Which will simply make my Repositories abstract wrappers for &lt;em&gt;ObjectContext&lt;/em&gt;. On the other hand the benefit is very low. My target was to decouple repository and EF! And the benefit cannot be mentioned. Because if I want to achieve decoupling that means I can use same &lt;em&gt;IDataContext&lt;/em&gt; interface with another Data Access Helper class such as LINQ to SQL context or any other Data Access produced by any ORM. And this might not be possible.&lt;/p&gt;  &lt;p&gt;So I decided to put a limitation to my &lt;em&gt;IDataContext&lt;/em&gt; and make it coupled with EF. Then the main usage of &lt;em&gt;IDataContext&lt;/em&gt; would be for TDD support.&lt;/p&gt;  &lt;p&gt;I would like to refer to a great post made by &lt;a href="http://weblogs.asp.net/rashid/" target="_blank" rel="contact,friend"&gt;Kazi&lt;/a&gt; about &lt;a href="http://weblogs.asp.net/rashid/archive/2009/02/19/100-unit-testable-linq-to-sql-repository.aspx" target="_blank" rel="tag"&gt;how to build 100% Testable LINQ to SQL Repositories&lt;/a&gt;. I am actually applying his idea on EF.&lt;/p&gt;  &lt;p&gt;I will not talk about Repositories responsibilities, because they are clearly defined in DDD. But there is not harm if you made your Data Access Layer generated from any ORM coupled with Repositories. It will ease the development and keep everything be in the right direction.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Code Updated:&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Because I changed my design, I've updated my code to remove few methods and simplify &lt;em&gt;IDataContext.&lt;/em&gt;&lt;/p&gt;  &lt;p&gt;   &lt;div class="wlWriterSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:9e6723b0-c841-4bb2-bc69-96624bca126e" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;pre name="code" class="c#:nocontrols"&gt;public interface IDataContext
{
    IQueryable&amp;lt;Category&amp;gt; CategoryDataSource { get; }
    IQueryable&amp;lt;Product&amp;gt; ProductDataSource { get; }
    IQueryable&amp;lt;Supplier&amp;gt; SupplierDataSource { get; }

    IQueryable&amp;lt;T&amp;gt; GetQueryable&amp;lt;T&amp;gt;(string queryString) 
        where T: EntityObject;

    void AddObject&amp;lt;T&amp;gt;(string entitySetName, T entity) 
        where T : EntityObject;

    void InsertOnSubmit&amp;lt;T&amp;gt;(string entitySetName, T entity) 
        where T : EntityObject;
    
    void DeleteOnSubmit&amp;lt;T&amp;gt;(T entity) 
        where T : EntityObject;
    
    void SubmitChanges();
}

public partial class NorthwindDataContext : IDataContext
{
    private IQueryable&amp;lt;Category&amp;gt; _categorySet;
    private IQueryable&amp;lt;Product&amp;gt; _productSet;
    private IQueryable&amp;lt;Supplier&amp;gt; _supplierSet;
    
    public IQueryable&amp;lt;Category&amp;gt; CategoryDataSource
    {
        get
        {
            if (_categorySet == null)
            {
                _categorySet = GetQueryable&amp;lt;Category&amp;gt;("[CategorySet]");
            }
            return _categorySet;
        }
    }
    
    public IQueryable&amp;lt;Product&amp;gt; ProductDataSource
    {
        get
        {
            if (_productSet == null)
            {
                _productSet = GetQueryable&amp;lt;Product&amp;gt;("[ProductSet]");
            }
            return _productSet;
        }
    }
    
    public IQueryable&amp;lt;Supplier&amp;gt; SupplierDataSource
    {
        get
        {
            if (_supplierSet == null)
            {
                _supplierSet = GetQueryable&amp;lt;Supplier&amp;gt;("[SupplierSet]");
            }
            return _supplierSet;
        }
    }

    public virtual IQueryable&amp;lt;T&amp;gt; GetQueryable&amp;lt;T&amp;gt;(string queryString) where T : EntityObject
    {
        return base.CreateQuery&amp;lt;T&amp;gt;(queryString);
    }

    public void InsertOnSubmit&amp;lt;T&amp;gt;(string entitySetName, T entity)
        where T : EntityObject
    {
        AddObject&amp;lt;T&amp;gt;(entitySetName, entity);
    }

    public void DeleteOnSubmit&amp;lt;T&amp;gt;(T instance)
        where T : EntityObject
    {
        DeleteObject(instance);
    }

    public virtual void AddObject&amp;lt;T&amp;gt;(string entitySetName, T entity)
        where T : EntityObject
    {
        base.AddObject(entitySetName, entity);
    }
    
    public new virtual void DeleteObject(object instance)
    {
        base.DeleteObject(instance);
    }
    
    public void SubmitChanges()
    {
        base.SaveChanges(true);
    }
}&lt;/pre&gt;&lt;/div&gt;

  &lt;br /&gt;Unit Test Code:&lt;/p&gt;

&lt;div class="wlWriterSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:5d74da6f-1199-4649-8353-8c82ea8c036a" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;pre name="code" class="c#"&gt;[TestClass]
public class NorthwindDataContextTest
{
    private readonly Mock&amp;lt;NorthwindDataContext&amp;gt; _context;
    private readonly List&amp;lt;Category&amp;gt; _categories;
    private readonly List&amp;lt;Product&amp;gt; _products;
    private readonly List&amp;lt;Supplier&amp;gt; _suppliers;
    public NorthwindDataContextTest()
    {
        _context = new Mock&amp;lt;NorthwindDataContext&amp;gt;(ConfigurationManager
                   .ConnectionStrings["NorthwindDataContext"]
                   .ConnectionString);
        _categories = new List&amp;lt;Category&amp;gt;();
        _products = new List&amp;lt;Product&amp;gt;();
        _suppliers = new List&amp;lt;Supplier&amp;gt;();
    }

    [TestMethod]
    public void NorthwindDataContext_CategoryDataSource_Should_Call_GetQueryable()
    {
        _context.Expect(c =&amp;gt; c.GetQueryable&amp;lt;Category&amp;gt;("[CategorySet]"))
                .Returns(_categories.AsQueryable())
                .Verifiable();

        Assert.IsNotNull(_context.Object.CategoryDataSource);

        _context.Verify();
    }

    [TestMethod]
    public void NorthwindDataContext_ProductDataSource_Should_Call_GetQueryable()
    {
        _context.Expect(c =&amp;gt; c.GetQueryable&amp;lt;Product&amp;gt;("[ProductSet]"))
                .Returns(_products.AsQueryable())
                .Verifiable();

        Assert.IsNotNull(_context.Object.ProductDataSource);

        _context.Verify();
    }

    [TestMethod]
    public void NorthwindDataContext_SupplierDataSource_Should_Call_GetQueryable()
    {
        _context.Expect(c =&amp;gt; c.GetQueryable&amp;lt;Supplier&amp;gt;("[SupplierSet]"))
                .Returns(_suppliers.AsQueryable())
                .Verifiable();

        Assert.IsNotNull(_context.Object.SupplierDataSource);
        
        _context.Verify();
    }

    [TestMethod]
    public void NorthwindDataContext_Insert_Should_Call_AddObject()
    {
        var category = Category.CreateCategory(1, String.Empty);

        _context.Expect(c =&amp;gt; c.AddObject("[CategorySet]",category)).Verifiable();

        _context.Object.InsertOnSubmit("[CategorySet]", category);

        _context.Verify();
    }

    [TestMethod]
    public void NorthwindDataContext_Delete_Should_Call_DeleteObject()
    {
        var category = Category.CreateCategory(1, String.Empty);

        _context.Expect(c =&amp;gt; c.DeleteObject(category)).Verifiable();

        _context.Object.DeleteOnSubmit(category);

        _context.Verify();
    }
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Conclusion:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blogs.zdnet.com/microsoft/?p=1457" target="_blank"&gt;EF is not testable by nature&lt;/a&gt;, you'll have to find a way to do unit testing independent of EF. That is why I am keeping updating my code till I reach to a an ideal way. Maybe not the best way but at least a method that will ease this job for the time being. I think it might also result in writing your own EF code generator using EdmGem.&lt;/p&gt;

&lt;p&gt;I've update the code on this post, you can &lt;a href="http://mosesofegypt.net/file.axd?file=TDDWithEFSampleModified.zip" target="_blank" rel="enclosure"&gt;download it here&lt;/a&gt;.&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?a=MLPlqqws"&gt;&lt;img src="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?d=41" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?a=fou7EPma"&gt;&lt;img src="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?i=fou7EPma" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?a=eIbxjFmK"&gt;&lt;img src="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?d=50" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?a=beAAqnTJ"&gt;&lt;img src="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?d=43" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?a=cQUG4sGz"&gt;&lt;img src="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?i=cQUG4sGz" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/MosesOfEgyptBlog/~4/LAgkhgRsz0I" height="1" width="1"/&gt;</description><dc:publisher xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:publisher><pingback:server xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/pingback.axd</pingback:server><pingback:target xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/post.aspx?id=325c0305-01a3-4f66-8996-fb1c0c4dc2da</pingback:target><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">4</slash:comments><trackback:ping xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">http://mosesofegypt.net/trackback.axd?id=325c0305-01a3-4f66-8996-fb1c0c4dc2da</trackback:ping><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/post/DDDandTDDwithEFPart1bReview.aspx#comment</wfw:comment><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/syndication.axd?post=325c0305-01a3-4f66-8996-fb1c0c4dc2da</wfw:commentRss><feedburner:origLink>http://mosesofegypt.net/post.aspx?id=325c0305-01a3-4f66-8996-fb1c0c4dc2da</feedburner:origLink></item><item><title>Domain Driven Design &amp; Test Driven Development\Design with Entity Framework, Part 1.a Refactoring &amp; Unit Testing</title><link>http://feedproxy.google.com/~r/MosesOfEgyptBlog/~3/k-cjKyijTXE/post.aspx</link><category>Entity Framework</category><category>LINQ</category><category>Software Design</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:creator><pubDate>Tue, 10 Feb 2009 15:49:55 PST</pubDate><guid isPermaLink="false">http://mosesofegypt.net/post.aspx?id=7e7f995d-0887-4f08-b430-17f5c887e1be</guid><description>&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/wl1TEnVqXY3OPvVo9i1iHrx5XGM/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/wl1TEnVqXY3OPvVo9i1iHrx5XGM/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/wl1TEnVqXY3OPvVo9i1iHrx5XGM/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/wl1TEnVqXY3OPvVo9i1iHrx5XGM/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;p&gt;In &lt;a href="http://mosesofegypt.net/post/TDDandTDDWithEFPart1BuildingDomainObjectModel.aspx" rel="tag"&gt;previous post&lt;/a&gt; I talked about building domain model for Northwind using Entity Framework. I used the generated &lt;em&gt;ObjectContext&lt;/em&gt; class which is &lt;em&gt;NorthwindDataContext&lt;/em&gt; as the basic Data Access Layer &lt;em&gt;Helper&lt;/em&gt;. But my &lt;em&gt;NorthwindDataContext&lt;/em&gt; is implementing custom interface I created in order to be able to make my Data Access Layer testable as well as to be independent from EF.&lt;/p&gt;  &lt;p&gt;My target is to achieve decoupling between EF and all layers above it. This include Repository classes. This might not be of a big benefit to everyone, because my repositories implementation will still dependent on &lt;em&gt;IDataContext&lt;/em&gt;. But for me it will help to do TDD more smoothly regardless of my underlying data access layer. Beside it might allow me in future to be able to switch from EF to LINQ to SQL and just implement my &lt;em&gt;IDataContext&lt;/em&gt; interface for LINQ to SQL.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://mosesofegypt.net/file.axd?file=TDDWithEFSample.zip" rel="enclosure"&gt;Source code&lt;/a&gt; is attached to this post, feel free to &lt;a href="http://mosesofegypt.net/file.axd?file=TDDWithEFSample.zip" rel="enclosure"&gt;download&lt;/a&gt; it and explore the code&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Refactoring of IDataContext and Models:&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;After some discussion with &lt;a href="http://landman-code.blogspot.com/"&gt;Davy Landman&lt;/a&gt; and getting some feedback from him. I made some refactoring to &lt;em&gt;IDataContext &lt;/em&gt;although me an him have different ideas few conflicts. So basically here is what I need from &lt;em&gt;IDataContext&lt;/em&gt; to support:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Being able to retrieve all records of Categories, Products &amp;amp; Supplier&lt;/li&gt;    &lt;li&gt;Being able to filter these entities by unique identifier to return single record.&lt;/li&gt;    &lt;li&gt;Being able to register new record for insertion or deletion.&lt;/li&gt;    &lt;li&gt;Being able to persist changes to the underlying data source.&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;The above list is not the only features I need, in future it must grow, like being able to filter Products by category and so on.&lt;/p&gt;  &lt;p&gt;I hear some of&amp;#160; you saying, What! this is the job of repository classes to build queries and perform data access. and I will answer yes and I totally agree, but I provide &lt;em&gt;IDataContext&lt;/em&gt; as a huge repository of queries that is actually wrapped by Repositories. I think this concept is applicable with some ORM tools such as EF and LINQ to SQL. But might not work for other things such as classical Data Access Layers and NHibernate. So simply I consider &lt;em&gt;IDataContext&lt;/em&gt; part of repository classes.&lt;/p&gt;  &lt;p&gt;The implementation of &lt;em&gt;IDataContext&lt;/em&gt; which is &lt;em&gt;NorthwindDataContext&lt;/em&gt; class includes some helper methods &amp;amp; properties to assist me to work with EF and being able to test it. But generally I am hiding most the features provided by EF generated code with these methods &amp;amp; properties. Because simply that generated code is not testable and you cannot use to set expectations when you start to use mocking.&lt;/p&gt;  &lt;p&gt;Below is the class diagram of my refactored model with data access layer helper:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://mosesofegypt.net/image.axd?picture=WindowsLiveWriter/DomainDrivenDesignTestDrivenDevelopmentD_13EF7/NorthwindClassDiagram_2.jpg" rel="lightbox"&gt;&lt;img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="296" alt="NorthwindClassDiagram" src="http://mosesofegypt.net/image.axd?picture=WindowsLiveWriter/DomainDrivenDesignTestDrivenDevelopmentD_13EF7/NorthwindClassDiagram_3.jpg" width="404" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Also I zoomed on &lt;em&gt;NorthwindDataContext&lt;/em&gt; class and provided the following diagram with comments about 2 helper methods:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://mosesofegypt.net/image.axd?picture=WindowsLiveWriter/DomainDrivenDesignTestDrivenDevelopmentD_13EF7/NorthwindDataContextClassDiagram_4.jpg" rel="lightbox"&gt;&lt;img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="334" alt="NorthwindDataContextClassDiagram" src="http://mosesofegypt.net/image.axd?picture=WindowsLiveWriter/DomainDrivenDesignTestDrivenDevelopmentD_13EF7/NorthwindDataContextClassDiagram_5.jpg" width="404" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Here is the code of &lt;em&gt;GetEnumrable&lt;/em&gt; &amp;amp; &lt;em&gt;GetFilteredDataSource&lt;/em&gt; methods with explanation of each method's role :&lt;/p&gt;  &lt;p&gt;   &lt;div class="wlWriterSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:d288ba26-c3c6-4bff-b570-cfb3865faf1e" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;/// &amp;lt;summary&amp;gt;
/// Used as helper method to provide casting from EDM primative data type 
/// (generated model entity) such Category to model Interface such ICategory 
/// which is implemented by the generated EDM entity class.
/// &amp;lt;/summary&amp;gt;
/// &amp;lt;typeparam name="I"&amp;gt;Type of the model interface&amp;lt;/typeparam&amp;gt;
/// &amp;lt;typeparam name="E"&amp;gt;
/// Type of the EF primative data type (generated model entity)
/// "E" (model entity) must implement "I" (model interface)
/// &amp;lt;/typeparam&amp;gt;
/// &amp;lt;param name="datasource"&amp;gt;Data source to be filtered&amp;lt;/param&amp;gt;
/// &amp;lt;param name="filter"&amp;gt;Filter expression used to filter datasource&amp;lt;/param&amp;gt;
/// &amp;lt;returns&amp;gt;IEnumrable of I (model interface)&amp;lt;/returns&amp;gt;
private static IEnumerable&amp;lt;I&amp;gt; GetEnumerable&amp;lt;I, E&amp;gt;(IQueryable&amp;lt;E&amp;gt; datasource, Expression&amp;lt;Func&amp;lt;E, bool&amp;gt;&amp;gt; filter)
 where I : class, IEntity
 where E : class, I
{
 var filteredQry = (filter != null) ? datasource.Where(filter) : datasource;
 foreach (var item in filteredQry)
     yield return item as I;
}

/// &amp;lt;summary&amp;gt;
/// Takes as a parameter Linq filter Expression to be used to filter data source set
/// such as CategorySet. 
/// This will help to provide filters that will perform filtering on underlying 
/// data source side and not in memory filtering using LINQ to Objects.
/// This method calls GetEnumerable&amp;lt;I, E&amp;gt; providing it with the correct data source set.
/// &amp;lt;/summary&amp;gt;
/// &amp;lt;typeparam name="I"&amp;gt;Type of the model interface&amp;lt;/typeparam&amp;gt;
/// &amp;lt;typeparam name="E"&amp;gt;
/// Type of the EF primative data type (generated model entity)
/// "E" (model entity) must implement "I" (model interface)
/// &amp;lt;/typeparam&amp;gt;
/// &amp;lt;param name="datasource"&amp;gt;Data source to be filtered&amp;lt;/param&amp;gt;
/// &amp;lt;param name="filter"&amp;gt;Filter expression used to filter datasource&amp;lt;/param&amp;gt;
/// &amp;lt;returns&amp;gt;IQueryable of I (model interface)&amp;lt;/returns&amp;gt;
private IQueryable&amp;lt;I&amp;gt; GetFilteredDataSource&amp;lt;I, E&amp;gt;(Expression&amp;lt;Func&amp;lt;E, bool&amp;gt;&amp;gt; filter)
 where I : class, IEntity
 where E : class, I
{
 IQueryable&amp;lt;E&amp;gt; queryable = null;

 if (typeof(I) == typeof(ICategory))
     queryable = this.CategoryTable as IQueryable&amp;lt;E&amp;gt;;
 else if (typeof(I) == typeof(IProduct))
     queryable = this.ProductTable as IQueryable&amp;lt;E&amp;gt;;
 else if (typeof(I) == typeof(ISupplier))
     queryable = this.SupplierTable as IQueryable&amp;lt;E&amp;gt;;

 return GetEnumerable&amp;lt;I, E&amp;gt;(queryable, filter).AsQueryable() as IQueryable&amp;lt;I&amp;gt;;
}&lt;/pre&gt;&lt;/div&gt;

  &lt;br /&gt;Now if I wanted to filter Category set data source by Category Id I shall use GetFilteredDataSource by a way or another. That is why I am using in FindXxxById methods as the following:

  &lt;div class="wlWriterSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:63851325-bbc8-48d0-837d-89a415eec0f7" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;pre name="code" class="c:nogutter:nocontrols"&gt;public ICategory FindCategoryById(int id)
{
 return this.GetFilteredDataSource&amp;lt;ICategory, Category&amp;gt;(c =&amp;gt; c.Id == id).FirstOrDefault();
}

public IProduct FindProductById(int id)
{
 return this.GetFilteredDataSource&amp;lt;IProduct, Product&amp;gt;(c =&amp;gt; c.Id == id).FirstOrDefault();
}

public ISupplier FindSupplierById(int id)
{
 return this.GetFilteredDataSource&amp;lt;ISupplier, Supplier&amp;gt;(c =&amp;gt; c.Id == id).FirstOrDefault();
}&lt;/pre&gt;&lt;/div&gt;
&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Coding Testable EF ObjectContext Class:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Before starting this point, let me clarify what does Testable means. Testable means being able to write Unit Test code that can test your coded independent of the environment, database or anything similar. And being able to mock your classes. Simply being able to write Unit Tests that follow the guide lines mentioned in my &lt;a href="http://mosesofegypt.net/post/FirstStepstowardTDD.aspx" rel="tag"&gt;earlier post&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;That was my target for &lt;em&gt;NorthwindDataContext&lt;/em&gt; class, is being able to test it independent of the database, and confirm the success of my test by doing integration test that also success.&lt;/p&gt;

&lt;p&gt;Someone would say and why I want to test something that is already tested (by Microsoft)? Well because later you'll need to test classes that depends on this class. If you used the auto generated EF code as it is you'll not be able to set expectations out of it to be able to test independent of the database.&lt;/p&gt;

&lt;p&gt;The auto generated code is not testable, because it requires to hit the database and you cannot mock it. In order to be able to stay way of database you need to have an alternative. The common alternative is in memory storage using Lists.&lt;/p&gt;

&lt;p&gt;Using generated EntitySet types such as &lt;em&gt;CategorySet&lt;/em&gt; properties will require database. To workaround this I created few helper public virtual properties that wrap auto generated EntitySets such as &lt;em&gt;CategorySet&lt;/em&gt; as the following:&lt;/p&gt;

&lt;div class="wlWriterSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:1a1dda1c-b372-4f22-a535-5fa4dd50f06c" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;/// &amp;lt;summary&amp;gt;
/// Return EF Coupled IQueryable of Category. Used for testing purpose only
/// &amp;lt;/summary&amp;gt;
public virtual IQueryable&amp;lt;Category&amp;gt; CategoryTable
{
 get{ return this.CategorySet; }
}
/// &amp;lt;summary&amp;gt;
/// Return EF Coupled IQueryable of Product. Used for testing purpose only
/// &amp;lt;/summary&amp;gt;
public virtual IQueryable&amp;lt;Product&amp;gt; ProductTable
{
 get{ return this.ProductSet; }
}
/// &amp;lt;summary&amp;gt;
/// Return EF Coupled IQueryable of Supplier. Used for testing purpose only
/// &amp;lt;/summary&amp;gt;
public virtual IQueryable&amp;lt;Supplier&amp;gt; SupplierTable
{
 get{ return this.SupplierSet; }
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Now why these helper properties are virtual public. Public because I want to be able to access them throw my unit test classes. Virtual because &lt;a href="http://code.google.com/p/moq/"&gt;Moq&lt;/a&gt; will require these properties to be virtual in order to be able to override them to return my specified expectations. Same concept is applied to some public methods such &lt;em&gt;AddObject&lt;/em&gt; and &lt;em&gt;DeleteObject&lt;/em&gt; methods. But because these properties or methods are not interface based; so they will not be accessible through repositories as I'll show on my upcoming posts.&lt;/p&gt;

&lt;p&gt;The above properties are invoked through &lt;em&gt;GetFilteredDataSource&lt;/em&gt; method.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Writing Unit Test for EF ObjectContext Class:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In TDD is supposed to write your tests first, fail them and start fix what is broken and make your code run. Then do refactoring over and over to formalize your code. My first test attempt will fail because of NotImplementedException thrown by &lt;em&gt;IDataContext&lt;/em&gt; methods in NorthwindDataContext class. My test basically want to test the following:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Calling IDataContext (&lt;em&gt;Categories&lt;/em&gt;,&lt;em&gt;Products&lt;/em&gt; or &lt;em&gt;Suppliers&lt;/em&gt;) properties should not return null.&lt;/li&gt;

  &lt;li&gt;Calling IDataContext &lt;em&gt;FindXxxById&lt;/em&gt; methods should return correct Xxx entity.&lt;/li&gt;

  &lt;li&gt;Calling IDataContext &lt;em&gt;Insert&lt;/em&gt; should call &lt;em&gt;AddObject&lt;/em&gt; Method of &lt;em&gt;NorthwindDataContext&lt;/em&gt; to insure that the object is being added to proper Entity Set and prepared for persistence.&lt;/li&gt;

  &lt;li&gt;Calling IDataContext &lt;em&gt;Delete&lt;/em&gt; should call &lt;em&gt;DeleteObject&lt;/em&gt; Method of &lt;em&gt;NorthwindDataContext&lt;/em&gt; to insure that the object is being marked for deletion.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I am using &lt;a href="http://code.google.com/p/moq/" target="_blank"&gt;Moq&lt;/a&gt; to assist me in my TDD. In this attempt I will need a mock instance of &lt;em&gt;NorthwindDataContext&lt;/em&gt; to simulate its work independent of the underlying database. Also I am initializing few lists to act as in memory storage.&lt;/p&gt;

&lt;p&gt;
  &lt;div class="wlWriterSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:8723c286-34b5-4b0c-b541-b870ca3d6c08" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;private readonly Mock&amp;lt;NorthwindDataContext&amp;gt; _context;
private readonly List&amp;lt;Category&amp;gt; _categories;
private readonly List&amp;lt;Product&amp;gt; _products;
private readonly List&amp;lt;Supplier&amp;gt; _suppliers;
public NorthwindDataContextTest()
{
    _context = new Mock&amp;lt;NorthwindDataContext&amp;gt;(ConfigurationManager
                                             .ConnectionStrings["NorthwindDataContext"]
                                             .ConnectionString);
    _categories = new List&amp;lt;Category&amp;gt;();
    _products = new List&amp;lt;Product&amp;gt;();
    _suppliers = new List&amp;lt;Supplier&amp;gt;();
}&lt;/pre&gt;&lt;/div&gt;
&lt;/p&gt;

&lt;p&gt;On line 7 to 9 I am initializing new mock instance of &lt;em&gt;NorthwindDataCotext&lt;/em&gt;. I am getting a connection string from application configuration file. you might ask why I would need a connection string. Actually this is a must thing in order to be able to load your EDM model. If you didn't provide this connection string the mocking will fail. The connection string in this test just specify the path of CSDL, SSDL and MSL. In my case they are embedded resources:&lt;/p&gt;

&lt;p&gt;
  &lt;div class="wlWriterSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:cff170f8-ab8a-43af-ad79-ca6e2b6f58e9" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;pre name="code" class="xml:nogutter:nocontrols"&gt;&amp;lt;configuration&amp;gt;
 &amp;lt;connectionStrings&amp;gt;
  &amp;lt;add name="NorthwindDataContext" 
       connectionString="metadata=res://*/Edm.Northwind.csdl|res://*/Edm.Northwind.ssdl|res://*/Edm.Northwind.msl;provider=System.Data.SqlClient;"
       providerName="System.Data.EntityClient" /&amp;gt;
 &amp;lt;/connectionStrings&amp;gt;
&amp;lt;/configuration&amp;gt;&lt;/pre&gt;&lt;/div&gt;
&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Writing Test Initialization with Visual Studio.Net Unit Testing:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;As I am using VS.Net unit testing tools I am using the provided unit testing facilities. Such as Test Initialization feature. This is just a method marked with TestInitialize attribute as the following:&lt;/p&gt;

&lt;p&gt;
  &lt;div class="wlWriterSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:e3ab8afd-1f2c-4f93-ac3b-0a3fc79d7620" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;[TestInitialize]
public void TestInitialize()
{
    _context.ExpectGet(c =&amp;gt; c.CategoryTable)
			.Returns(_categories.AsQueryable());
    
	_context.ExpectGet(c =&amp;gt; c.ProductTable)
			.Returns(_products.AsQueryable());
    
	_context.ExpectGet(c =&amp;gt; c.SupplierTable)
			.Returns(_suppliers.AsQueryable());
}&lt;/pre&gt;&lt;/div&gt;
&lt;/p&gt;

&lt;p&gt;I am using the mocked NorthwindDataContext to set expectation to the helper properties I mentioned earlier. Again to be able to set expectations with &lt;a href="http://code.google.com/p/moq/" target="_blank"&gt;Moq&lt;/a&gt; you'll need public virtual methods or properties. So Whenever a call is made to CategoryTable or ProductTable or SupplierTable the specified expectation for each one should be returned.&lt;/p&gt;

&lt;p&gt;Now I want to test &lt;em&gt;IDataContext&lt;/em&gt; properties (&lt;em&gt;Categories&lt;/em&gt;, &lt;em&gt;Products&lt;/em&gt; and &lt;em&gt;Suppliers&lt;/em&gt;):&lt;/p&gt;

&lt;p&gt;
  &lt;div class="wlWriterSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:ce0b5b15-ea45-4818-9091-960bb1a8d625" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;[TestMethod]
public void NorthwindDataContext_Categories_Returns_Category_Set()
{
    Assert.IsNotNull(_context.Object.Categories);
}
[TestMethod]
public void NorthwindDataContext_Products_Returns_Product_Set()
{
    Assert.IsNotNull(_context.Object.Products);
}
[TestMethod]
public void NorthwindDataContext_Suppliers_Returns_Supplier_Set()
{
    Assert.IsNotNull(_context.Object.Suppliers);
}&lt;/pre&gt;&lt;/div&gt;
&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint:&lt;/strong&gt; &lt;em&gt;Unit test method in VS.Net are marked with TestMethod Attribute. Every time one of the test method being call TestInitialize Method will be called first as well as test class constructor.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;I wish to trace the call of the above code. &lt;em&gt;_context.Object&lt;/em&gt; will return a mocked instance of &lt;em&gt;NorthwindDataContext&lt;/em&gt;. When calling Categories property this property invokes &lt;em&gt;GetFilteredDataSource&lt;/em&gt; method which in turn calls &lt;em&gt;CategoryTable&lt;/em&gt; helper property. When &lt;em&gt;CategoryTable&lt;/em&gt; property is called it will return the expectation I specified in &lt;em&gt;TestInitialize&lt;/em&gt; method. Same thing is applied for the other properties.&lt;/p&gt;

&lt;p&gt;Time to test filtering methods such as &lt;em&gt;FindCategoryById&lt;/em&gt;. I write test for such methods by preparing data to test with, then set my expectation. Finally perform tested method call and assert returned results, just as the following:&lt;/p&gt;

&lt;div class="wlWriterSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:4a8651b6-a91c-4df1-bdb2-b02c1fd6d444" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;[TestMethod]
public void NorthwindDataContext_FindCategoryById_Returns_Correct_Category()
{
 //Prepare test data.
 for (int i = 1; i &amp;lt; 11;i++ )
     _categories.Add(Category.CreateCategory(i, String.Empty));

 //Get existing Id.
 int id = _categories[0].Id;

 //Set Expectation
 _context.ExpectGet(c =&amp;gt; c.CategoryTable).Returns(_categories.AsQueryable());

 //Perform Test
 var category = _context.Object.FindCategoryById(id);

 //Assert
 Assert.IsNotNull(category);
 Assert.AreEqual(category.Id, id);
}&lt;/pre&gt;&lt;/div&gt;

&lt;br /&gt;

&lt;p&gt;Note that I am testing single thing per unit test method. That doesn't mean you should perform single assert. In the above method I am testing one then but doing 2 asserts, one to ensure that the returned result is not null and the other assert to ensure that the returned result is the desired one.&lt;/p&gt;

&lt;p&gt;My final test is to test &lt;em&gt;Insert&lt;/em&gt; and &lt;em&gt;Delete&lt;/em&gt; method. Actually in these tests I just want to check if &lt;em&gt;AddObject&lt;/em&gt; or &lt;em&gt;DeleteObject&lt;/em&gt; methods are being called. These helper methods uses internally the EF generated code to add object to the context or mark it for deletion. I don't want to test the underlying EF generated code, I just want to test mine.&lt;/p&gt;

&lt;p&gt;
  &lt;div class="wlWriterSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:2cc30a5b-8b95-47fc-8f32-cfa4173eea82" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;[TestMethod]
public void NorthwindDataContext_Insert_Should_Call_AddObject()
{
 var category = Category.CreateCategory(1, String.Empty);

 _context.Expect(c =&amp;gt; c.AddObject(category)).Verifiable();

 _context.Object.Insert(category);

 _context.Verify();
}&lt;/pre&gt;&lt;/div&gt;
&lt;/p&gt;

&lt;p&gt;On line 6 I am setting my expectation as a call to &lt;em&gt;AddObject&lt;/em&gt; method. And using Moq features I am asking to verify this call using &lt;em&gt;Verifiable&lt;/em&gt; method of the mocked object. On line 10 I am calling &lt;em&gt;Verify&lt;/em&gt; method of the mocked &lt;em&gt;NorthwindDataContext&lt;/em&gt;. This method will verify that &lt;em&gt;AddObject&lt;/em&gt; method is being called. If not the test will fail.&lt;/p&gt;

&lt;p&gt;After running my test I got them all Green.That was a happy ending. This code should run on your machine and produce green results as well. You can &lt;a href="http://mosesofegypt.net/file.axd?file=TDDWithEFSample.zip" target="_blank"&gt;download&lt;/a&gt; it and review the code and get me with some feedback and enhancements.&lt;/p&gt;

&lt;p&gt;I would like to thank &lt;a href="http://landman-code.blogspot.com/" target="_blank" rel="contact,friend"&gt;Davy Landman&lt;/a&gt; for his valuable ideas and thoughts and the references he provided me about DDD. I am new to DDD &amp;amp; TDD and I thought the best way to learn them is to share my thoughts with others, making mistakes and let somebody else correct me. So feel free to comment and provide me with more resources and ideas.&lt;/p&gt;

&lt;p&gt;As this post already grow long I will keep my integration test for the next post. Where I will show that my assumptions and expectations during TDD unit testing applies also on my Integration testing.&lt;/p&gt;

&lt;p&gt;Keep tuned. &lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?a=C50I6nyt"&gt;&lt;img src="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?d=41" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?a=RbhZZS1g"&gt;&lt;img src="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?i=RbhZZS1g" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?a=c2P0OznV"&gt;&lt;img src="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?d=50" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?a=eFU09Ezo"&gt;&lt;img src="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?d=43" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?a=TGQGo5nO"&gt;&lt;img src="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?i=TGQGo5nO" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/MosesOfEgyptBlog/~4/k-cjKyijTXE" height="1" width="1"/&gt;</description><dc:publisher xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:publisher><pingback:server xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/pingback.axd</pingback:server><pingback:target xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/post.aspx?id=7e7f995d-0887-4f08-b430-17f5c887e1be</pingback:target><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">6</slash:comments><trackback:ping xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">http://mosesofegypt.net/trackback.axd?id=7e7f995d-0887-4f08-b430-17f5c887e1be</trackback:ping><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/post/DDD-And-TDD-with-EF-Part1A-Refactoring-And-Unit-Testing.aspx#comment</wfw:comment><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/syndication.axd?post=7e7f995d-0887-4f08-b430-17f5c887e1be</wfw:commentRss><feedburner:origLink>http://mosesofegypt.net/post.aspx?id=7e7f995d-0887-4f08-b430-17f5c887e1be</feedburner:origLink></item><item><title>Domain Driven Design &amp; Test Driven Design With Entity Framework, Part 1 Building Domain Object Model</title><link>http://feedproxy.google.com/~r/MosesOfEgyptBlog/~3/Vb_kVdHLMEY/post.aspx</link><category>Entity Framework</category><category>Software Design</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:creator><pubDate>Wed, 04 Feb 2009 16:38:23 PST</pubDate><guid isPermaLink="false">http://mosesofegypt.net/post.aspx?id=e9877048-ce0d-40d1-94d7-f13c8a955730</guid><description>&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/LyTx6imRNe7Z-nExdc22vtPgdQM/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/LyTx6imRNe7Z-nExdc22vtPgdQM/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/LyTx6imRNe7Z-nExdc22vtPgdQM/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/LyTx6imRNe7Z-nExdc22vtPgdQM/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Introduction:&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;In &lt;a href="http://mosesofegypt.net/post/FirstStepstowardTDD.aspx"&gt;my previous&lt;/a&gt; post I talked about definitions of TDD as specified in different sources. Here in this post I'll walk-through applied Domain Driven Design &amp;amp; Test Driven Design on &lt;a href="http://msdn.microsoft.com/en-us/library/bb399572.aspx" target="_blank"&gt;Entity Framework&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;I assume that you already know &lt;a href="http://msdn.microsoft.com/en-us/library/bb399572.aspx" target="_blank"&gt;Entity Framework&lt;/a&gt; and how to create your entity data modes using Visual Studio.Net 2008 with SP1.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Domain Driven Design &amp;amp; Entity Framework:&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;To simplify things, I am using Northwind database. Basically I'll expose 3 tables in this database, Categories, Products &amp;amp; Suppliers. Those will be my domain objects as Category,Product and Supplier classes.&lt;/p&gt;  &lt;p&gt;Each Category object might contain one or more items of Product. Same thing for Supplier object as it might provide one or more items of Product. That means Product object must have a Supplier and a Category. I defined those criteria for my Domain Objects.&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;I started to create my Domain Object using &lt;a href="http://msdn.microsoft.com/en-us/library/bb399572.aspx" target="_blank"&gt;Entity Framework&lt;/a&gt;. My Entity Data Model looks like the below diagram:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://mosesofegypt.net/image.axd?picture=WindowsLiveWriter/DomainDrivenDesignTestDri.NetUnitTesting_13DBE/NorthwindEdmDiagram_2.jpg" rel="lightbox"&gt;&lt;img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="251" alt="Northwind Edm Diagram" src="http://mosesofegypt.net/image.axd?picture=WindowsLiveWriter/DomainDrivenDesignTestDri.NetUnitTesting_13DBE/NorthwindEdmDiagram_3.jpg" width="404" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;I'm not done yet. I thought that just using my generated code is not enough. And I want to abstract my Domain Object as much as possible incase I want to use different tool other than &lt;a href="http://msdn.microsoft.com/en-us/library/bb399572.aspx" target="_blank"&gt;Entity Framework&lt;/a&gt; such as LINQ to SQL.&lt;/p&gt;  &lt;p&gt;So I created 3 contracts (interfaces), that actually represents my Domain Objects: &lt;em&gt;ICategory&lt;/em&gt;, &lt;em&gt;IProduct&lt;/em&gt; and &lt;em&gt;ISupplier&lt;/em&gt;. These contracts has parent interface called &lt;em&gt;IEntity&lt;/em&gt; that has only one property called &lt;em&gt;Id&lt;/em&gt;. Assuming that all my Domain Objects should have a unique key property of type integer and called &lt;em&gt;Id&lt;/em&gt;.&lt;/p&gt;  &lt;p&gt;I made my generated models to implement those interfaces (thanks to partial classes). In fact those interfaces contains exactly same property names and types as specified in the above models. Except that I renamed the navigation properties in the generated models to include the word Internal such as &lt;em&gt;ProductsInternal&lt;/em&gt; navigation property in Category concrete data model class.&lt;/p&gt;  &lt;p&gt;Below are the definition of each interface:&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;div class="wlWriterSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:6e294913-9740-4575-b29c-14a4982a7480" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;pre name="code" class="c#:nocontrols"&gt;public interface IEntity
{
    int Id { get; }
}

public interface ICategory : IEntity
{
    string CategoryName { get; set; }
    string Description { get; set; }
    byte[] Picture { get; set; }
    IQueryable&amp;lt;IProduct&amp;gt; Products { get; }
}

public interface IProduct : IEntity
{
    string ProductName { get; set; }
    string QuantityPerUnit { get; set; }
    decimal? UnitPrice { get; set; }
    short? UnitsInStock { get; set; }
    short? UnitsOnOrder { get; set; }
    short? ReorderLevel { get; set; }
    bool Discontinued { get; set; }
    ICategory Category { get; }
    ISupplier Supplier { get; }
}

public interface ISupplier : IEntity
{
    string CompanyName { get; set;}
    string ContactName { get; set; }
    string ContactTitle { get; set; }
    string Address { get; set; }
    string Country { get; set; }
    string City { get; set; }
    string Region { get; set; }
    string PostalCode { get; set; }
    string Phone { get; set; }
    string Fax { get; set; }
    string HomePage { get; set; }
    IQueryable&amp;lt;IProduct&amp;gt; Products { get; }
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;I would like to clarify few points about the above code. As you notice on lines 11, 23, 24 and 40. These lines of code define navigation properties. For example &lt;em&gt;ICategory&lt;/em&gt; domain object interface has a navigation property &lt;em&gt;IQueryable&amp;lt;IProduct&amp;gt; Products&lt;/em&gt; that retrieves all products related to a specific category. I made this to be independent of the under laying generated code by Entity Framework. This is actually abstraction and removing dependency between your Domain Object Definitions and its implementations. The definitions should define what these models should contain and do. The implementation should specify the how. Your concrete models might be coupled with certain technology, as in my case. My concrete models are Entity Framework Models.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Entity Framework as Data Access Layer:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Entity Framework provide Data Services classes that I will use as my data access layer assets. For example the generated &lt;em&gt;ObjectContext&lt;/em&gt; class, this is actually acts as my proxy to the underlying datasource and called entity container by Entity Framework Schema. But Entity Framework doesn't support -in version 1- persistence ignorance! Which will make working with my Domain Object Model interfaces hard and may be impossible. Because for example the generate ObjectContext class doesn't have anything that would return a result set of &lt;em&gt;ICategory&lt;/em&gt;. And guess what you'll not be able to cast &lt;em&gt;ObjectQuery&amp;lt;Category&amp;gt;&lt;/em&gt; to &lt;em&gt;IQueryable&amp;lt;ICategory&amp;gt;&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Take this as an example the generate NorthwindDataContext has a property called CategorySet. This property returns ObjectQuery&amp;lt;Category&amp;gt;. You might think of calling this property like this: 
  &lt;br /&gt;&lt;em&gt;context.CategorySet.Cast&amp;lt;ICategory&amp;gt;().AsQueryable();&lt;/em&gt; 

  &lt;br /&gt;But this is simply will not work and will throw an exception as &lt;em&gt;Cast&lt;/em&gt; extension method will only work if you are casting to correct &lt;em&gt;&lt;u&gt;generate Entity Models primitive types&lt;/u&gt;&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Another issue calling &lt;em&gt;CategorySet&lt;/em&gt; property or calling &lt;em&gt;CreateQuery&amp;lt;T&amp;gt;&lt;/em&gt; method of the base ObjectContext class would result in creating a query that will require hitting the database when starting to iterate through the results. This issue violates one of the guide lines of performing TDD which is to be independent of the working environment by simulating environmental dependencies such as databases, file systems, networks, queues etc...&lt;/p&gt;

&lt;p&gt;To over come these issues simply I created another interface that include basic data access functionality. I learned this idea from &lt;a href="http://www.codeplex.com/Kigg/" target="_blank"&gt;Kigg&lt;/a&gt; the open source project that is running live on &lt;a title="http://dotnetshoutout.com/" href="http://dotnetshoutout.com/"&gt;http://dotnetshoutout.com/&lt;/a&gt;. This project apply the same idea on Linq To SQL context object class.&lt;/p&gt;

&lt;p&gt;I called the interface &lt;em&gt;IDataContext&lt;/em&gt; and defined the basic operations I will need in this interface:&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;div class="wlWriterSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:e2a56ca1-b8cd-4656-90d6-dfcb7d025bb4" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;pre name="code" class="c#:nocontrols"&gt;public interface IDataContext
{
 IQueryable&amp;lt;ICategory&amp;gt; Categories { get; }
 IQueryable&amp;lt;IProduct&amp;gt; Products { get; }
 IQueryable&amp;lt;ISupplier&amp;gt; Suppliers { get; }
    
 IQueryable&amp;lt;TInterface&amp;gt; GetDataSource&amp;lt;TInterface, TEntity&amp;gt;(Func&amp;lt;TEntity, bool&amp;gt; filterExpression)
     where TInterface : class, IEntity
     where TEntity : class;

 TEntityInterface GetEntityById&amp;lt;TEntityInterface&amp;gt;(int id) 
     where TEntityInterface : class, IEntity;

 void Insert&amp;lt;TEntityInterface&amp;gt;(TEntityInterface instance) 
     where TEntityInterface : class, IEntity;
    
 void Delete&amp;lt;TEntityInterface&amp;gt;(TEntityInterface instance) 
     where TEntityInterface : class, IEntity;
    
 void SubmitChanges();
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;Again the generated ObjectContext class by Entity Framework should implement this interface. Below is the implementation of IDataContext:&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;div class="wlWriterSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:022ed488-6347-4186-a424-cc10d87e6219" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;&lt;pre name="code" class="c#:nocontrols"&gt;public partial class NorthwindDataContext : IDataContext
{
 public static IEnumerable&amp;lt;TInterface&amp;gt; GetEnumerable&amp;lt;TInterface, TEntity&amp;gt;(IQueryable&amp;lt;TEntity&amp;gt; query, Func&amp;lt;TEntity, bool&amp;gt; filter)
  where TInterface : class, IEntity
  where TEntity : class
 {
  var filteredQuery = (filter != null) ? 
	(from item in query select item).Where(filter) : query;
  foreach (var item in filteredQuery)
  {
   yield return item as TInterface;
  }
 }

 public virtual IQueryable&amp;lt;Category&amp;gt; CategoryTable
 {
  get{return this.CategorySet;}
 }
 public virtual IQueryable&amp;lt;Product&amp;gt; ProductTable
 {
  get{return this.ProductSet;}
 }
 public virtual IQueryable&amp;lt;Supplier&amp;gt; SupplierTable
 {
  get{return this.SupplierSet;}
 }
 
 public IQueryable&amp;lt;ICategory&amp;gt; Categories
 {
  get
  {
   return this.GetDataSource&amp;lt;ICategory, Category&amp;gt;(null);
  }
 }
    
 public IQueryable&amp;lt;IProduct&amp;gt; Products
 {
  get
  {
   return this.GetDataSource&amp;lt;IProduct, Product&amp;gt;(null);
  }
 }
    
 public IQueryable&amp;lt;ISupplier&amp;gt; Suppliers
 {
  get
  {
   return this.GetDataSource&amp;lt;ISupplier, Supplier&amp;gt;(null);
  }
 }

 public IQueryable&amp;lt;TInterface&amp;gt; GetDataSource&amp;lt;TInterface, TEntity&amp;gt;(Func&amp;lt;TEntity, bool&amp;gt; filter)
  where TInterface : class, IEntity
  where TEntity : class
 {
  IQueryable&amp;lt;TEntity&amp;gt; queryable = null;
  if (typeof(TInterface) == typeof(ICategory))
     queryable = this.CategoryTable as IQueryable&amp;lt;TEntity&amp;gt;;                
  if (typeof(TInterface) == typeof(IProduct))
     queryable = this.ProductTable as IQueryable&amp;lt;TEntity&amp;gt;;
  if (typeof(TInterface) == typeof(ISupplier))
     queryable = this.SupplierTable as IQueryable&amp;lt;TEntity&amp;gt;;

  return GetEnumerable&amp;lt;TInterface, TEntity&amp;gt;(queryable, filter).AsQueryable() as IQueryable&amp;lt;TInterface&amp;gt;;
 }
    
 public TEntity GetEntityById&amp;lt;TEntity&amp;gt;(int id) 
  where TEntity : class, IEntity
 {
  if (typeof(TEntity) == typeof(ICategory))
  {
   return this.GetDataSource&amp;lt;ICategory,Category&amp;gt;(c =&amp;gt; c.Id == id).SingleOrDefault() as TEntity;
  }
  else if (typeof(TEntity) == typeof(IProduct))
  {
   return this.GetDataSource&amp;lt;IProduct,Product&amp;gt;(c =&amp;gt; c.Id == id).SingleOrDefault() as TEntity;
  }
  else if (typeof(TEntity) == typeof(ISupplier))
  {
   return this.GetDataSource&amp;lt;ISupplier, Supplier&amp;gt;(c =&amp;gt; c.Id == id).SingleOrDefault() as TEntity;
  }
  else
   return null;
  }

 public void Insert&amp;lt;TEntity&amp;gt;(TEntity instance) 
  where TEntity : class, IEntity
 {
  AddObject&amp;lt;TEntity&amp;gt;(instance);
 }
 public void Delete&amp;lt;TEntity&amp;gt;(TEntity instance)
  where TEntity : class, IEntity
 {
  DeleteObject(instance);
 }
 public virtual void AddObject&amp;lt;TEntity&amp;gt;(TEntity instance) 
  where TEntity : class, IEntity
 {
  Type type = typeof(TEntity);
  if (type == typeof(ICategory))
  {
   this.AddToCategorySet(instance as Category);
  }
  else if (type == typeof(IProduct))
  {
   this.AddToProductSet(instance as Product);
  }
  else if (type == typeof(ISupplier))
  {
   this.AddToSupplierSet(instance as Supplier);
  }
 }
    
 public new virtual void DeleteObject(object instance)
 {
  base.DeleteObject(instance);
 }
    
 public void SubmitChanges()
 {
  base.SaveChanges(true);
 }
}&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;An important thing to note, now after implementing &lt;em&gt;IDataContext&lt;/em&gt;, from my code I should use &lt;em&gt;NorthwindDataContext&lt;/em&gt; as &lt;em&gt;IDataContext&lt;/em&gt;. Which means my consumer application which could be a Repository class or anything else should not know anything about &lt;em&gt;NorthwindDataContext&lt;/em&gt; and be totally independent of it. &lt;/p&gt;

&lt;p&gt;Using &lt;em&gt;NorthwindDataContext&lt;/em&gt; as my data access layer through &lt;em&gt;IDataContext&lt;/em&gt; is something that can be specified using Dependency Injection.&lt;/p&gt;

&lt;p&gt;&lt;font color="#800000"&gt;&lt;em&gt;Start Updated Content&lt;/em&gt;&lt;/font&gt;

  &lt;br /&gt;I would like to explain 2 methods above which are &lt;em&gt;IEnumerable&amp;lt;TInterface&amp;gt; GetEnumerable&amp;lt;TInterface, TEntity&amp;gt;(IQueryable&amp;lt;TEntity&amp;gt; query, Func&amp;lt;TEntity, bool&amp;gt; filter)&lt;/em&gt; and &lt;em&gt;IQueryable&amp;lt;TInterface&amp;gt; GetDataSource&amp;lt;TInterface, TEntity&amp;gt;(Func&amp;lt;TEntity, bool&amp;gt; filter)&lt;/em&gt;...&lt;/p&gt;

&lt;p&gt;&lt;em&gt;GetEnumerable&lt;/em&gt; method is helper method, I used it to overcome casting limitations in LINQ to Entities. This method takes &lt;em&gt;IQueryable&amp;lt;TEntity&amp;gt;&lt;/em&gt; as a parameter. &lt;em&gt;TEntity&lt;/em&gt; is supposed to be the concrete model class while &lt;em&gt;IQueryable&amp;lt;TEntity&amp;gt;&lt;/em&gt; will be actually &lt;em&gt;ObjectQuery&amp;lt;TEntity&amp;gt;&lt;/em&gt;. This method is used by &lt;em&gt;XxxDataSource&lt;/em&gt; properties. It will help me much in testing my Data Access Layer as I will show in the next part soon.&lt;/p&gt;

&lt;p&gt;About &lt;em&gt;GetDataSource&lt;/em&gt; method, this one also to overcome LINQ to Entities limitations. In fact in implementation &lt;em&gt;GetDataSource&lt;/em&gt; makes call to &lt;em&gt;GetEnumerable&lt;/em&gt; and pass a filter expression to it. Someone would say why Filter as you could use property &lt;em&gt;Categories&lt;/em&gt; and build a LINQ statement over it and that is it, something like context.Categories.Where(c=&amp;gt;c.Id == 1); Well, I highly recommend to review &lt;a href="http://landman-code.blogspot.com/"&gt;Davy Landman&lt;/a&gt; comment on this post which shows that the code snippet context.Categories.Where(c=&amp;gt;c.Id == 1) would perform filter in memory and not on database side. Maybe I should call this method &lt;em&gt;GetFilteredDataSource&lt;/em&gt;.

  &lt;br /&gt;&lt;em&gt;&lt;font color="#800000"&gt;End Updated Content&lt;/font&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;I didn't complete the implementation of my domain model objects, basically the navigation properties. There are different&amp;#160; ideas to implement them so I will keep that to be done later to differentiate between different approaches I have in mind.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What about TDD first?!&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You might ask why I didn't start with TDD as supposed?! Well, I had an idea that my domain object should be ready before starting writing testing code! Someone would say write test and then refactor! I say 2 faces one coin. I made my design, and I will write its Test every time I finish part of it. Now that I finished this part, I would start writing my unit test code. In next part I will talk about Unit Testing with VS.Net tools and &lt;a href="http://code.google.com/p/moq/" target="_blank"&gt;Moq&lt;/a&gt;. Applying TDD to my design to ensure that my code works fine with my expectations. And later I will do another unit testing for integration to ensure that both TDD and Integration Testing where both built on the correct assumptions.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://code.google.com/p/moq/" target="_blank"&gt;Moq&lt;/a&gt; will help me to achieve 3 guide lines:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Separates or simulates environmental dependencies such as databases, file systems, networks, queues, and so on. Tests that exercise these will not run fast, and a failure does not give meaningful feedback about what the problem actually is. &lt;/li&gt;

  &lt;li&gt;Runs and passes in isolation. If the tests require special environmental setup or fail unexpectedly, then they are not good unit tests. Change them for simplicity and reliability. Tests should run and pass on any machine. &lt;/li&gt;

  &lt;li&gt;Often uses stubs and mock objects. If the code being tested typically calls out to a database or file system, these dependencies must be simulated, or mocked. These dependencies will ordinarily be abstracted away by using &lt;em&gt;&lt;u&gt;interfaces&lt;/u&gt;&lt;/em&gt; &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="http://code.google.com/p/moq/" target="_blank"&gt;Moq&lt;/a&gt; will help me to set expectations for my returning results of certain methods. For example &lt;em&gt;GetEnumerable&lt;/em&gt; method I mentioned above should return &lt;em&gt;IEnumerable&amp;lt;TInterface&amp;gt;&lt;/em&gt;. I can simulate its operation using &lt;a href="http://code.google.com/p/moq/" target="_blank"&gt;Moq&lt;/a&gt; and set an expectation to its call where expected and also define the return results. To simulate database results I will use in memory collections which I will specify as return results whenever possible with the assist of &lt;a href="http://code.google.com/p/moq/" target="_blank"&gt;Moq&lt;/a&gt;. We will look at what &lt;a href="http://code.google.com/p/moq/" target="_blank"&gt;Moq&lt;/a&gt; can provide us in my next post.&lt;/p&gt;

&lt;p&gt;You can &lt;a href="http://mosesofegypt.net/file.axd?file=TDDWithEFSample.zip"&gt;download my initiative project&lt;/a&gt; and Stay Tuned for the upcoming part.&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?a=SJ7Ci70B"&gt;&lt;img src="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?d=41" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?a=RWNZZHGi"&gt;&lt;img src="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?i=RWNZZHGi" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?a=xktx7V1S"&gt;&lt;img src="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?d=50" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?a=irp90piK"&gt;&lt;img src="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?d=43" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?a=Ce5PQuF4"&gt;&lt;img src="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?i=Ce5PQuF4" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/MosesOfEgyptBlog/~4/Vb_kVdHLMEY" height="1" width="1"/&gt;</description><dc:publisher xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:publisher><pingback:server xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/pingback.axd</pingback:server><pingback:target xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/post.aspx?id=e9877048-ce0d-40d1-94d7-f13c8a955730</pingback:target><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">13</slash:comments><trackback:ping xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">http://mosesofegypt.net/trackback.axd?id=e9877048-ce0d-40d1-94d7-f13c8a955730</trackback:ping><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/post/TDDandTDDWithEFPart1BuildingDomainObjectModel.aspx#comment</wfw:comment><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/syndication.axd?post=e9877048-ce0d-40d1-94d7-f13c8a955730</wfw:commentRss><feedburner:origLink>http://mosesofegypt.net/post.aspx?id=e9877048-ce0d-40d1-94d7-f13c8a955730</feedburner:origLink></item><item><title>First Steps toward Test Driven Design\Development</title><link>http://feedproxy.google.com/~r/MosesOfEgyptBlog/~3/_a-yoUKmbBU/post.aspx</link><category>Entity Framework</category><category>Learning &amp; Certifications</category><category>Software Design</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:creator><pubDate>Tue, 27 Jan 2009 17:33:06 PST</pubDate><guid isPermaLink="false">http://mosesofegypt.net/post.aspx?id=e957dd77-6d76-4914-891f-74b2b30853cb</guid><description>&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/9txto0Y9wPv9jgNcHQySJmJGCCg/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/9txto0Y9wPv9jgNcHQySJmJGCCg/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/9txto0Y9wPv9jgNcHQySJmJGCCg/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/9txto0Y9wPv9jgNcHQySJmJGCCg/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Introduction:&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;I'm totally new to TDD world. I saw many sample open source projects that based on TDD and DDD but I explored only 2 of them, the &lt;a href="http://blog.wekeroad.com/mvc-storefront/mvc-storefront-part-1/" target="_blank"&gt;MVC Storefront&lt;/a&gt; and &lt;a href="http://www.codeplex.com/Kigg/" target="_blank"&gt;Kigg&lt;/a&gt; (&lt;a href="http://dotnetshoutout.com/" target="_blank"&gt;see it live&lt;/a&gt;). I was very lucky actually to go deep with &lt;a href="http://www.codeplex.com/Kigg/" target="_blank"&gt;Kigg&lt;/a&gt; source code and I found it one of the most clean and testable code I ever seen. With out single line of comment you can understand what this code is doing. Special thanks to &lt;a href="http://weblogs.asp.net/rashid/" target="_blank"&gt;Kazi Mansur Rashid&lt;/a&gt; every member of this project for such great work.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Quotes:&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;This encourage me to start practically learning TDD and apply it. So I started to &lt;a href="http://www.google.com/search?q=test+driven+development" target="_blank"&gt;search about TDD&lt;/a&gt;. In the following few lines I am going to list few quotes I caught from different sources:&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&amp;quot;&lt;em&gt;&lt;strong&gt;Test-driven development&lt;/strong&gt; (TDD) is a &lt;/em&gt;&lt;a href="http://en.wikipedia.org/wiki/Software_development"&gt;&lt;em&gt;software development&lt;/em&gt;&lt;/a&gt;&lt;em&gt; technique that uses short development iterations based on pre-written &lt;/em&gt;&lt;a href="http://en.wikipedia.org/wiki/Test_case"&gt;&lt;em&gt;test cases&lt;/em&gt;&lt;/a&gt;&lt;em&gt; that define desired improvements or new functions. Each iteration produces code necessary to pass that iteration's tests. Finally, the programmer or team &lt;/em&gt;&lt;a href="http://en.wikipedia.org/wiki/Code_refactoring"&gt;&lt;strong&gt;&lt;em&gt;refactors&lt;/em&gt;&lt;/strong&gt;&lt;/a&gt;&lt;em&gt; the code to accommodate changes. A key TDD concept is that preparing tests before coding facilitates rapid feedback changes. Note that test-driven development is a &lt;/em&gt;&lt;a href="http://en.wikipedia.org/wiki/Software_engineering"&gt;&lt;em&gt;software design method&lt;/em&gt;&lt;/a&gt;&lt;em&gt;, not merely a method of testing&lt;/em&gt;&amp;quot; -Source: &lt;a href="http://en.wikipedia.org/wiki/Test-driven_development" target="_blank"&gt;Wikipedia&lt;/a&gt;-&lt;/p&gt;  &lt;p&gt;&amp;quot;&lt;em&gt;The first step is to quickly add a test, basically just enough code to fail.&amp;#160; Next you run your tests, often the complete test suite although for sake of speed you may decide to run only a subset, to ensure that the new test does in fact fail.&amp;#160; You then update your functional code to make it pass the new tests.&amp;#160; The fourth step is to run your tests again.&amp;#160; If they fail you need to update your functional code and retest.&amp;#160; Once the tests pass the next step is to start over (you may first need to refactor any duplication out of your design as needed, turning TFD into TDD).&amp;quot;&lt;/em&gt; -Source: &lt;a href="http://www.agiledata.org/essays/tdd.html" target="_blank"&gt;agiledata.org, Introduction to Test Driven Design (TDD)&lt;/a&gt;-&lt;/p&gt;  &lt;p&gt;&amp;quot;&lt;em&gt;Test-driven development (TDD) is an advanced technique of using automated unit tests to drive the design of software and force decoupling of dependencies. The result of using this practice is a comprehensive suite of unit tests that can be run at any time to provide feedback that the software is still working. This technique is heavily emphasized by those using Agile development methodologies. The motto of test-driven development is &amp;quot;Red, Green, Refactor. Where Red: Create a test and make it fail, Green: Make the test pass by any means necessary. Refactor: Change the code to remove duplication in your project and to improve the design while ensuring that all tests still pass&lt;/em&gt;&amp;quot; -Source: &lt;a href="http://msdn.microsoft.com/en-us/library/aa730844.aspx" target="_blank"&gt;MSDN, Guidelines for Test-Driven Development by Jeffrey Palermo&lt;/a&gt;-&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;My thoughts:&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;TDD isn't something new, but lately there was a loud talks around the community about it. Anyway after reading the above introduction quotes, I start to compare them. They are all agree you start by writing your test scenarios (coding them). Then you run them to fail. Later you start the iteration of fixing your code to make it pass the test. And finally you do refactoring. Maybe the word finally isn't the correct word, for me refactoring will be an occurring task that you'll keep doing to optimize your code and keep it clean.&lt;/p&gt;  &lt;p&gt;One good thing about TDD is that your code will be CLEAN. I tried it myself and soon I'll share my code which I made against Entity Framework. My learning source was &lt;a href="http://www.codeplex.com/Kigg/" target="_blank"&gt;Kigg&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;TDD &amp;amp; Entity Framework:&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;While I was trying to write tests for my Entity Data Model, I realized that my tests will require to hit the database!! Which is acceptable in case I am doing integration testing. So I had to find another way to apply TDD with EF. &lt;a href="http://www.codeplex.com/Kigg/" target="_blank"&gt;Kigg&lt;/a&gt; was the key for the solution because it does the same with LINQ to SQL, However, EF and LINQ to Entities is different than LINQ to SQL. Many things that are supported and expected work with LINQ to SQL and LINQ to Object just don't fit with LINQ to Entities. You can have read my posts regarding such not supported features in LINQ to Entities.&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://mosesofegypt.net/post/LINQ-to-Entities-what-is-not-supported.aspx" target="_blank"&gt;LINQ to Entities, what is not supported?&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a href="http://mosesofegypt.net/post/LINQ-to-Entities-Workarounds-on-what-is-not-supported.aspx" target="_blank"&gt;LINQ to Entities, Workarounds on what is not supported&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Guidelines listed at &amp;quot;&lt;a href="http://msdn.microsoft.com/en-us/library/aa730844.aspx" target="_blank"&gt;Guidelines for Test-Driven Development&lt;/a&gt;&amp;quot; by Jeffrey Palermo made my understand to Unit testing in TDD clear. I am going to list few of these guidelines but I hardly recommend that you have a look at them because they aren't too much:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Separates or simulates environmental dependencies such as databases, file systems, networks, queues, and so on. Tests that exercise these will not run fast, and a failure does not give meaningful feedback about what the problem actually is. &lt;/li&gt;    &lt;li&gt;Runs and passes in isolation. If the tests require special environmental setup or fail unexpectedly, then they are not good unit tests. Change them for simplicity and reliability. Tests should run and pass on any machine. &lt;/li&gt;    &lt;li&gt;Often uses stubs and mock objects. If the code being tested typically calls out to a database or file system, these dependencies must be simulated, or mocked. These dependencies will ordinarily be abstracted away by using interfaces. &lt;/li&gt;    &lt;li&gt;Clearly reveals its intention. Another developer can look at the test and understand what is expected of the production code. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;That was all for this post, soon I'll start to post about TDD &amp;amp; DDD with samples. And I will show how to follow TDD while working with Entity Framework and being independent of it. The above guidelines where like magic words to me. Keep tuned.&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?a=g4dhRjbT"&gt;&lt;img src="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?d=41" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?a=4N2kbOy1"&gt;&lt;img src="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?i=4N2kbOy1" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?a=SC7nhDRU"&gt;&lt;img src="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?d=50" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?a=OOz3JEx4"&gt;&lt;img src="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?d=43" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?a=sk2RDnKG"&gt;&lt;img src="http://feeds.feedburner.com/~f/MosesOfEgyptBlog?i=sk2RDnKG" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/MosesOfEgyptBlog/~4/_a-yoUKmbBU" height="1" width="1"/&gt;</description><dc:publisher xmlns:dc="http://purl.org/dc/elements/1.1/">mosessaur</dc:publisher><pingback:server xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/pingback.axd</pingback:server><pingback:target xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/">http://mosesofegypt.net/post.aspx?id=e957dd77-6d76-4914-891f-74b2b30853cb</pingback:target><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">8</slash:comments><trackback:ping xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">http://mosesofegypt.net/trackback.axd?id=e957dd77-6d76-4914-891f-74b2b30853cb</trackback:ping><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/post/FirstStepstowardTDD.aspx#comment</wfw:comment><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://mosesofegypt.net/syndication.axd?post=e957dd77-6d76-4914-891f-74b2b30853cb</wfw:commentRss><feedburner:origLink>http://mosesofegypt.net/post.aspx?id=e957dd77-6d76-4914-891f-74b2b30853cb</feedburner:origLink></item></channel></rss>
