<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://blogs.msdn.com/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>system.data.objects dev guy</title><link>http://blogs.msdn.com/dsimmons/default.aspx</link><description>Ramblings about ADO.Net, the Entity Framework, and other random things from a dev guy.</description><dc:language>en-US</dc:language><generator>CommunityServer 2.1 SP1 (Build: 61025.2)</generator><item><title>It’s time to rip up EntityBag and throw it away</title><link>http://blogs.msdn.com/dsimmons/archive/2009/11/05/it-s-time-to-rip-up-entitybag-and-throw-it-away.aspx</link><pubDate>Thu, 05 Nov 2009 18:36:05 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9918134</guid><dc:creator>dsimmons@microsoft.com</dc:creator><slash:comments>0</slash:comments><comments>http://blogs.msdn.com/dsimmons/comments/9918134.aspx</comments><wfw:commentRss>http://blogs.msdn.com/dsimmons/commentrss.aspx?PostID=9918134</wfw:commentRss><description>&lt;p&gt;A couple of years ago when the overall shape of what we would ship in the first release of the entity framework became apparent, I realized that one of the biggest issues users of that release would fight with was creating N-tier applications.&amp;#160; So I started a project to explore the space by creating something I called EntityBag.&amp;#160; In spite of the fact that I wasn’t too thrilled with the overall approach, I thought it would be a good exercise and if nothing else it would help illuminate the issues with building this kind of application on the EF and demonstrate to folks what techniques they could use with the EF to solve these problems.&amp;#160; The result of this investigation was a series of blog posts and a sample project which I uploaded to code gallery.&amp;#160; You can check out the project at: &lt;a href="http://code.msdn.microsoft.com/entitybag/"&gt;http://code.msdn.microsoft.com/entitybag/&lt;/a&gt;&amp;#160; That site also has links to each of the relevant blog posts which is where the real interesting data lives.&lt;/p&gt;  &lt;p&gt;At the time that I created EntityBag (mostly January 2008), the version of the Entity Framework was called “beta 3”, and it was before the first RTM of the product.&amp;#160; Unfortunately, when the first version was finally released we included a change to by default generate classes which would serialize an entire graph of related entities as one (at beta 3 only one entity would serialize at a time) which ended up breaking EntityBag and the fix involved fairly major surgery.&amp;#160; From the beginning this project had never been intended as a full-quality production solution—I just wanted to teach people how they could use the EF to build the right solutions for their particular projects.&amp;#160; In addition I wanted to work with the team to produce a much better, long-term solution for N-tier apps, so whatever time I had available for this topic I poured into the next release of the EF (EF4) rather than into updating the EntityBag project.&lt;/p&gt;  &lt;h2&gt;&lt;/h2&gt;  &lt;h4&gt;&lt;u&gt;If not EntityBag, then what have we been doing for N-tier?&lt;/u&gt;&lt;/h4&gt;  &lt;p&gt;The team has been working hard to make N-Tier much easier with EF4, and the result is several key features that are available now when you combine &lt;a href="http://msdn.microsoft.com/en-us/vstudio/dd582936.aspx" target="_blank"&gt;Beta 2 of VS2010/.NET 4&lt;/a&gt; and yesterday’s release of what we call the &lt;a href="http://www.microsoft.com/downloads/details.aspx?displaylang=en&amp;amp;FamilyID=13fdfce4-7f92-438f-8058-b5b4041d0f01" target="_blank"&gt;EF Feature CTP 2&lt;/a&gt;.&amp;#160; &lt;/p&gt;  &lt;p&gt;The first critical addition to the product are core changes to the ObjectContext and ObjectStateManager APIs which make working with entities which spend some time detached from a context MUCH easier.&amp;#160; These changes were described about a year ago in this &lt;a href="http://blogs.msdn.com/efdesign/archive/2008/11/20/n-tier-improvements-for-entity-framework.aspx" target="_blank"&gt;post to the EF Design blog&lt;/a&gt;.&amp;#160; There have been a few small adjustments to the APIs as we went through the experience of the first and second betas for this release, but the core changes are all there along with much of the reasoning behind them.&amp;#160; &lt;/p&gt;  &lt;p&gt;Next, we added support for foreign-key relationships which allow FK properties to be added to entities, and the system does intelligent fixup between the FK properties and the collection and reference “navigation” properties which were the only representation of a relationship which the EF had in its first release.&amp;#160; FK relationships are important to N-Tier apps for two reasons: First off, they make it easier to support scenarios where you don’t want the perf hit (magnified in N-tier applications) of retrieving an entire object in order to establish a relationship.&amp;#160; With FK properties you can just set the key value for the relationship.&amp;#160; This was possible before by setting an EntityKey property, but that was harder than it should have been and MUCH harder (and sometimes impossible) when you have POCO entities.&amp;#160; Even more interesting for N-tier applications, though, is the fact that FK relationships give the EF the knowledge that a relationship’s persistence is fundamentally tied to a particular entity rather than being conceptually completely separate, and this is important because it allows the EF to use concurrency checks for the entity to cover concurrency checks for the relationship as well.&amp;#160; In the first release of the EF, the framework had no way to know from the conceptual model which if any entity “contained” the FK for the relationship so it performed concurrency checks for the relationships separately from the entities which meant that you needed the original value of a relationship not just the original value of whatever concurrency token you used for the entity.&amp;#160; Uggg…&amp;#160; That’s a little long-winded and obtuse, but the key point to realize is that having FK-relationships makes n-tier applications more efficient and intuitive in at least a couple of ways.&lt;/p&gt;  &lt;p&gt;Finally, we had resounding feedback in response to the initial N-tier post on the EF Design blog and in other places saying that while the core APIs were flexible and made things easier, there was still just too much work required to build end-to-end N-tier solutions.&amp;#160; So we created the self-tracking entities template which ships for now in Feature CTP 2 but will be in the box when .NET 4 launches on March 22, 2010.&amp;#160; Self-tracking entities won’t be right for everyone, and for those folks where they aren’t a great fit as is there will either be the option to modify the template (Long live T4!) or to write code by hand using the core API improvements on which the STE template is built.&amp;#160; If they do match your situation, though, they make things MUCH easier.&amp;#160; The amount of code required is dramatically less, and the functionality is really pretty great.&amp;#160; You can write simple service methods that return entities.&amp;#160; On your client (which does NOT require .Net 4 or any version of the entity framework—it works on silverlight, for instance) you can manipulate entity graphs by adding, deleting and modifying entities as well as splicing more than one graph together if you like, and the entities will keep track of the minimum required set of original values as well as whatever changes are made to them all by themselves.&amp;#160; NO BAGS OR OTHER EQUIPMENT REQUIRED.&amp;#160; The only constraint is that you must use the generated self-tracking entity code on your client (not a simple proxy).&amp;#160; Then back on your service, the code to reattach that graph to the context with appropriate original values and all the tracking information is literally one method call: ApplyChanges.&amp;#160; &lt;/p&gt;  &lt;h4&gt;&lt;u&gt;How can I learn more about all this?&lt;/u&gt;&lt;/h4&gt;  &lt;p&gt;In addition to the posts referenced above, I recommend taking a look at the &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 walkthrough&lt;/a&gt; which was published after the first release of the feature CTP.&amp;#160; The current release of the STE template is a little different, but this is a great starting point, and more information will be available on the ado.net team blog soon.&amp;#160; The other resource to consider is that over the course of this summer I wrote a short series of articles in MSDN magazine about the topic of N-Tier in general and especially around using it with the Entity Framework.&amp;#160; The third article in that series just came out in the November issue, and it contains samples both of using STEs and using the core APIs to build other N-tier solutions.&amp;#160; You can find the articles online here:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/magazine/dd882522.aspx"&gt;Entity Framework: Anti-Patterns To Avoid In N-Tier Applications&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/magazine/ee321569.aspx"&gt;Entity Framework: N-Tier Application Patterns&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/magazine/ee335715.aspx" target="_blank"&gt;N-Tier Apps and the Entity Framework: Building N-Tier Apps with EF4&lt;/a&gt;&lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;So, death to EntityBag!&amp;#160; Long live EF4!&lt;/p&gt;  &lt;p&gt;- Danny&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9918134" width="1" height="1"&gt;</description></item><item><title>D3: Building Great Software is a Battle, Don’t Leave Any Assets on the Sidelines</title><link>http://blogs.msdn.com/dsimmons/archive/2009/06/30/d3-building-great-software-is-a-battle-don-t-leave-any-assets-on-the-sidelines.aspx</link><pubDate>Tue, 30 Jun 2009 12:01:56 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9809436</guid><dc:creator>dsimmons@microsoft.com</dc:creator><slash:comments>0</slash:comments><comments>http://blogs.msdn.com/dsimmons/comments/9809436.aspx</comments><wfw:commentRss>http://blogs.msdn.com/dsimmons/commentrss.aspx?PostID=9809436</wfw:commentRss><description>&lt;p&gt;&lt;a href="https://code.msdn.microsoft.com/Release/ProjectReleases.aspx?ProjectName=d3&amp;amp;ReleaseId=2904"&gt;Another D3 release&lt;/a&gt; is up.&amp;#160; This time I continued my focus on fundamentals.&amp;#160; Some of this is tedious, but as I establish solid mechanics I’m starting to gain some momentum.&amp;#160; The theme for today is using every last asset at your disposal to fight the battle to build great software.&amp;#160; When I first came to Microsoft a number of years ago, I was given the book &lt;a href="http://www.amazon.com/Writing-Solid-Code-Microsofts-Programming/dp/1556155514/ref=sr_1_1?ie=UTF8&amp;amp;s=books&amp;amp;qid=1246340176&amp;amp;sr=8-1"&gt;Writing Solid Code&lt;/a&gt; to help get me on the path to building world-class, reliable software.&amp;#160; While the book is a bit dated these days, the key message I took away is as important to me now as it was then:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;Writing software is &lt;strong&gt;&lt;u&gt;hard&lt;/u&gt;&lt;/strong&gt;.&amp;#160; So hard, in fact, that we need to play every trick in the book (and then some) if we’re going to have any hope of really getting it right.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The previous two versions of DPMud were just hacks, but this time around I’m trying to build something that demonstrates how the EF can be used as a key component in software to be proud of.&amp;#160; So, I ought to do things right—at least as much as I can given time constraints and everything else.&amp;#160; &lt;/p&gt;  &lt;h3&gt;&lt;/h3&gt;  &lt;h3&gt;Often Overlooked Asset #1: Analysis Tools&lt;/h3&gt;  &lt;p&gt;This weekend I spent some time enabling fxcop and stylecop for D3.&amp;#160; Actually I’m using the VSTS code analysis feature rather than fxcop because it’s built in to the VSTS download of VS2010 with really nice integration.&amp;#160; Turning it on was a breeze, I just right clicked on each of my projects, chose properties, clicked on the code analysis tab and then checked the Enable Code Analysis on Build box.&amp;#160; Actually, the first step was to download and install the VSTS flavor of VS2010 since I had initially just installed VS-Pro.&amp;#160; I was happy to find, though, that the web install was able to install VSTS on top of my existing pro install without any trouble and was even smart enough to skip all the minor components that were already on my machine…&lt;/p&gt;  &lt;p&gt;&lt;a href="http://www.the-simmons.net/images/D3BuildingGreatSoftwareisaBattleDontLeav_11CBB/CodeAnalysis.jpg"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Code-Analysis" border="0" alt="Code-Analysis" src="http://www.the-simmons.net/images/D3BuildingGreatSoftwareisaBattleDontLeav_11CBB/CodeAnalysis_thumb.jpg" width="661" height="471" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;The hard part was discovering just how many issues it could find even with the very small amount of code present in D3 so far.&amp;#160; As you can see above I’m just using the minimum recommended rules right now, and even with that I had to fix quite a few issues.&amp;#160; Most of them were essentially cosmetic things, but it did catch a place where I was doing string concatenation of a SQL query that should have been using a parameter.&amp;#160; There wasn’t any user input in sight, so I didn’t really have to worry about an injection attack, but it’s still a much better practice to use parameters wherever possible so I was happy to fix it.&amp;#160; At some point I expect that I’ll go back and crank the rule-level up even higher, but there were enough issues when I did that which were more about personal preference than really being super important (like requiring that assembly names begin with a capital letter) that I decided it wasn’t worth the effort just yet.&lt;/p&gt;  &lt;p&gt;I also downloaded stylecop and turned it on.&amp;#160; It’s a little more work since it’s not part of the core product, but like fxcop it really was surprisingly easy to turn on and then the real work was making the project comply.&amp;#160; I’m so glad that I did it now rather than later in the project, because keeping things going as I make incremental changes appears quite easy—the hard part is in the conversion.&amp;#160; If you have a large amount of code already, I would still recommend making the switch to these tools, but you might want to checkout the stylecop team blog where there is a post about ways to make sure all new code is checked and then gradually convert older code.&amp;#160; Fxcop is probably a bit more difficult but still worth it.&lt;/p&gt;  &lt;p&gt;In order to turn on stylecop, I copied the binaries for the tool to a directory under my source control, modified the batch file I load for my development environment to set an environment variable pointing to the directory where stylecop is present.&amp;#160; Then I unloaded each csproj, edited the XML and added one import element pointing to the stylecop targets file (I put mine next to the Import element for the standard csharp targets):&lt;/p&gt;  &lt;div id="codeSnippetWrapper"&gt;   &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"&gt;&lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;Import&lt;/span&gt; &lt;span style="color: #ff0000"&gt;Condition&lt;/span&gt;&lt;span style="color: #0000ff"&gt;=&amp;quot;'$(StyleCopPath)' != ''&amp;quot;&lt;/span&gt; &lt;span style="color: #ff0000"&gt;Project&lt;/span&gt;&lt;span style="color: #0000ff"&gt;=&amp;quot;$(StyleCopPath)\Microsoft.StyleCop.targets&amp;quot;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;/&amp;gt;&lt;/span&gt;&lt;/pre&gt;

  &lt;br /&gt;&lt;/div&gt;

&lt;p&gt;I put the condition attribute on it so if you don’t have the environment variable defined, it won’t try to load anything.&amp;#160; That way everything builds and works without stylecop.&amp;#160; (Code analysis also has the feature that if you don’t have it installed because you have VS-pro or something instead of VSTS then the configuration is just ignored and everything builds fine.)&amp;#160; Unfortunately, this same edit needs to be made to each csproj file so the trick is to make sure not to forget this when adding new assemblies in the future.&lt;/p&gt;

&lt;p&gt;By default both code analysis and stylecop report things as warnings, but I wanted to make certain everything was fixed so I also added a couple properties to the csproj files that change them into errors rather than warnings:&lt;/p&gt;

&lt;h3&gt;&lt;/h3&gt;

&lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"&gt;&lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;CodeAnalysisTreatWarningsAsErrors&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;true&lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;CodeAnalysisTreatWarningsAsErrors&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;StyleCopTreatErrorsAsWarnings&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;false&lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;StyleCopTreatErrorsAsWarnings&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;

&lt;div&gt;&amp;#160;&lt;/div&gt;

&lt;div&gt;One interesting issue that I ran into is that the stylecop VS integration doesn’t seem to work for VS2010.&amp;#160; Most of the time that’s fine because the VS integration is really only about editing the stylecop settings to turn off certain checks and the like.&amp;#160; The build integration that I describe above is all you need to make sure your source code is checked and warnings or errors appear in the VS IDE, but if you do have something you want to turn off (and in my case I decided to turn off the requirement to add documentation comments to everything as well as a few other small cosmetic things) then you need to edit the stylecop settings.&amp;#160; Fortunately if you double click on a Settings.Stylecop file in windows explorer, it will launch the UI for editing the settings independent of VS.&amp;#160; Probably there’s some other way to bootstrap this process, but for me the easiest way was to just launch the VS integration in VS2008 and then copy the settings file to my other project.&amp;#160; Once you have the right settings file, you just need to put it in the root directory of your project.&lt;/div&gt;

&lt;h3&gt;Asset #2: Check Constraints in the DB&lt;/h3&gt;

&lt;div&gt;I don’t recommend trying to add check constraints for everything, but there are places where the database is in a good position to enforce constraints on your data.&amp;#160; In many cases the EDM itself will enforce constraints—in the case of D3, the association between Actor and Room has cardinality 1:* rather than 0..1:* which means that every Actor must have a Room, and the EF will enforce that.&amp;#160; In the case of the association between Item and Room and the association between Item and Actor, we need there to be one and only one of those associations for each Item at any one time, and the EDM doesn’t have any way to represent that.&amp;#160; For both of these kinds of issues we will want to add business logic to the classes to make sure these things are prevented well before the time of saving changes, but it’s still good to enforce them in depth.&lt;/div&gt;

&lt;div&gt;&amp;#160;&lt;/div&gt;

&lt;div&gt;In the case of the item associations, I decided to use a check constraint in the database.&amp;#160; So I added a partial method call to the generated database creation code so that it’s easy to do this:&lt;/div&gt;

&lt;div&gt;&amp;#160;&lt;/div&gt;

&lt;div id="codeSnippetWrapper"&gt;
  &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"&gt;&lt;span style="color: #0000ff"&gt;internal&lt;/span&gt; &lt;span style="color: #0000ff"&gt;partial&lt;/span&gt; &lt;span style="color: #0000ff"&gt;class&lt;/span&gt; SqlDb&lt;br /&gt;{&lt;br /&gt;    &lt;span style="color: #0000ff"&gt;partial&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Customize()&lt;br /&gt;    {&lt;br /&gt;        &lt;span style="color: #008000"&gt;// Check Constraint which requires that Items live in either a room or on an actor.&lt;/span&gt;&lt;br /&gt;        &lt;span style="color: #0000ff"&gt;this&lt;/span&gt;.ExecuteCommand(&lt;span style="color: #006080"&gt;@&amp;quot;ALTER TABLE [dbo].[Items] &lt;br /&gt;                              WITH CHECK ADD CONSTRAINT [CK_Item_one_and_only_one_location] &lt;br /&gt;                              CHECK ((([Room_Id] IS NULL OR [Actor_Id] IS NULL) AND &lt;br /&gt;                                  NOT ([Room_Id] IS NULL AND [Actor_Id] IS NULL)))&amp;quot;&lt;/span&gt;);&lt;br /&gt;        &lt;span style="color: #0000ff"&gt;this&lt;/span&gt;.ExecuteCommand(&lt;span style="color: #006080"&gt;@&amp;quot;ALTER TABLE [dbo].[Items] CHECK CONSTRAINT [CK_Item_one_and_only_one_location]&amp;quot;&lt;/span&gt;);&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;

  &lt;br /&gt;&lt;/div&gt;

&lt;div&gt;Which brings me to the last asset in my list for today.&lt;/div&gt;

&lt;h3&gt;Asset #3: Unit Testing Your Brains Out&lt;/h3&gt;

&lt;div&gt;I’m sure this isn’t anything new to most of you, but like many others I’d say that I probably can’t emphasize enough the impact really drinking the unit testing kool-aide can have on your development.&amp;#160; D3 truly doesn’t have all that much code yet, and every time I add more tests I discover more issues.&amp;#160; Testing makes your code better as you go, plus it creates both documentation and automated verification which will help prevent regressions later.&lt;/div&gt;

&lt;h3&gt;Conclusions&lt;/h3&gt;

&lt;div&gt;There are always things you can do to make your code better.&amp;#160; Even more important, though, is to find things you can do to make CERTAIN that your code is better and will stay better.&amp;#160; Your software will benefit from it—D3 already has.&lt;/div&gt;

&lt;div&gt;&lt;/div&gt;

&lt;p&gt;- Danny&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9809436" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/dsimmons/archive/tags/Entity+Framework/default.aspx">Entity Framework</category><category domain="http://blogs.msdn.com/dsimmons/archive/tags/D3/default.aspx">D3</category></item><item><title>D3: Fun with Concurrency and Model First – Part 2</title><link>http://blogs.msdn.com/dsimmons/archive/2009/06/27/d3-fun-with-concurrency-and-model-first-part-2.aspx</link><pubDate>Sat, 27 Jun 2009 11:14:37 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9806444</guid><dc:creator>dsimmons@microsoft.com</dc:creator><slash:comments>0</slash:comments><comments>http://blogs.msdn.com/dsimmons/comments/9806444.aspx</comments><wfw:commentRss>http://blogs.msdn.com/dsimmons/commentrss.aspx?PostID=9806444</wfw:commentRss><description>&lt;p&gt;In &lt;a href="http://blogs.msdn.com/dsimmons/archive/2009/06/27/d3-fun-with-concurrency-and-model-first-part-1.aspx"&gt;my last post&lt;/a&gt; I began the story of how I added concurrency checking capabilities to D3—we conquered a bug in the model first workflow activities in VS 2010 beta 1.&amp;#160; Next we need to look into ways to customize the SSDL generated so that the concurrency column will end up with the RowVersion type that SQL Server will automatically update when any part of the row changes.&lt;/p&gt;  &lt;p&gt;This lead to the next surprise.&amp;#160; At first I thought that I would add a new custom activity to the workflow which would fix-up the SSDL, but this turned out to have its own complexities.&amp;#160; As it turns out, the model first process runs the workflow within the visual studio process which means the DLLs containing activities for the workflow are loaded in the same way other VS &lt;a href="http://www.the-simmons.net/images/D3FunwithConcurrencyandModelFirstPart2_57/DbGenxaml.jpg"&gt;&lt;img style="border-bottom: 0px; border-left: 0px; margin: 5px; display: inline; border-top: 0px; border-right: 0px" title="DbGen-xaml" border="0" alt="DbGen-xaml" align="left" src="http://www.the-simmons.net/images/D3FunwithConcurrencyandModelFirstPart2_57/DbGenxaml_thumb.jpg" width="316" height="389" /&gt;&lt;/a&gt;DLLs are loaded, namely from the VS install directories or from the GAC.&amp;#160; This also means if the DLL changes, you have to shutdown VS and restart it before model first will reflect the change.&amp;#160; Conclusion: If you want to create a general purpose activity that many folks will reuse, then this is a reasonable approach&amp;#160; You can carefully debug an activity and set something up to install it centrally.&amp;#160; But, if you need a one-off customization, this is just too hard.&amp;#160; &lt;/p&gt;  &lt;p&gt;So we’re looking into options to help here, but in the meantime I’ve discovered another approach which seems to work well.&amp;#160; The default workflow described in DbGen.xaml has two activities.&amp;#160; The first one takes the conceptual model and produces an MSL and SSDL string, while the second one takes the SSDL and produces something which will create the database (normally a SQL file, but after my first round of customizations for D3 it will produce a c-sharp file with a method that will create it).&amp;#160; &lt;/p&gt;  &lt;p&gt;It turns out, though, that the second activity under the covers is a general-purpose mechanism that can be configured to take in a string, run it through a T4 template and produce an output string.&amp;#160; The nice thing about using a template is that it allows you to write arbitrary code as a one-off in your solution and easily iterate on your design, modifying and rerunning without any need to restart VS, etc.&lt;/p&gt;  &lt;p&gt;Eureka!&amp;#160; The second activity can be used twice.&amp;#160; In between the two default activities, it can be inserted again and configured to take the SSDL in, transform it with a different template and send it on to the final activity.&amp;#160; In addition model first makes some useful bits of information like a path to the EDMX file available to the template, so we can access the CSDL in order to make better decisions about how to modify the SSDL.&lt;/p&gt;  &lt;p&gt;The relevant part of the resulting XAML looks like this:&lt;/p&gt;  &lt;div&gt;   &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"&gt;&lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;Sequence&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;    ...&lt;br /&gt;    &lt;span style="color: #0000ff"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #800000"&gt;edm1:SsdlToDdlActivity&lt;/span&gt; &lt;span style="color: #ff0000"&gt;ExistingSsdlInput&lt;/span&gt;&lt;span style="color: #0000ff"&gt;=&amp;quot;[ExistingSsdl]&amp;quot;&lt;/span&gt;&lt;br /&gt;                            &lt;span style="color: #ff0000"&gt;SsdlInput&lt;/span&gt;&lt;span style="color: #0000ff"&gt;=&amp;quot;[Ssdl]&amp;quot;&lt;/span&gt;&lt;br /&gt;                            &lt;span style="color: #ff0000"&gt;DdlOutput&lt;/span&gt;&lt;span style="color: #0000ff"&gt;=&amp;quot;[Ssdl]&amp;quot;&lt;/span&gt;&lt;br /&gt;                            &lt;span style="color: #ff0000"&gt;TemplatePath&lt;/span&gt;&lt;span style="color: #0000ff"&gt;=&amp;quot;DbGen\SsdlUseRowVersion.tt&amp;quot;&lt;/span&gt; &lt;span style="color: #0000ff"&gt;/&amp;gt;&lt;/span&gt;&lt;br /&gt;    ...&lt;br /&gt;&lt;span style="color: #0000ff"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #800000"&gt;Sequence&lt;/span&gt;&lt;span style="color: #0000ff"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;div&gt;&amp;#160;&lt;/div&gt;

&lt;div&gt;For D3, the fix-up we need is to find properties in the SSDL which correspond to properties in the CSDL with the following characteristics: type is binary, maxlength is 8, concurrency mode is fixed and store generation pattern is computed.&amp;#160; So we read the EDMX into an XElement tree in memory and then use LINQ to XML to gather the names of properties that need to be changed in the SSDL grouped by the name of the table in which they appear:&lt;/div&gt;

&lt;div&gt;&amp;#160;&lt;/div&gt;

&lt;div id="codeSnippetWrapper"&gt;
  &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"&gt;var query = from property &lt;span style="color: #0000ff"&gt;in&lt;/span&gt; csdl.Elements(edm + &lt;span style="color: #006080"&gt;&amp;quot;EntityType&amp;quot;&lt;/span&gt;).SelectMany(t =&amp;gt; t.Elements(edm + &lt;span style="color: #006080"&gt;&amp;quot;Property&amp;quot;&lt;/span&gt;))&lt;br /&gt;            &lt;span style="color: #0000ff"&gt;where&lt;/span&gt; (&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;)property.Attribute(&lt;span style="color: #006080"&gt;&amp;quot;Type&amp;quot;&lt;/span&gt;).Value == &lt;span style="color: #006080"&gt;&amp;quot;Binary&amp;quot;&lt;/span&gt; &amp;amp;&amp;amp;&lt;br /&gt;                  (&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;)property.Attribute(&lt;span style="color: #006080"&gt;&amp;quot;MaxLength&amp;quot;&lt;/span&gt;).Value == &lt;span style="color: #006080"&gt;&amp;quot;8&amp;quot;&lt;/span&gt; &amp;amp;&amp;amp;&lt;br /&gt;                  (&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;)property.Attribute(&lt;span style="color: #006080"&gt;&amp;quot;ConcurrencyMode&amp;quot;&lt;/span&gt;).Value == &lt;span style="color: #006080"&gt;&amp;quot;Fixed&amp;quot;&lt;/span&gt; &amp;amp;&amp;amp;&lt;br /&gt;                  (&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;)property.Attribute(store + &lt;span style="color: #006080"&gt;&amp;quot;StoreGeneratedPattern&amp;quot;&lt;/span&gt;).Value == &lt;span style="color: #006080"&gt;&amp;quot;Computed&amp;quot;&lt;/span&gt;&lt;br /&gt;            group (&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;)property.Attribute(&lt;span style="color: #006080"&gt;&amp;quot;Name&amp;quot;&lt;/span&gt;).Value&lt;br /&gt;            by entitySetName(property.Parent, csdl, edm);&lt;/pre&gt;

  &lt;br /&gt;&lt;/div&gt;

&lt;p&gt;This query depends on knowledge of the algorithm used by the CsdlToSsdlAndMslActivity to map conceptual model properties to the database—namely that the column names are the same as the property names on the entities and (at least for the base types of entity sets) the name of the table is the same as the name of the entity set that contains the type.&amp;#160; So we query the csdl for all the elements that represent properties which have the required facets and extract the name of the property, then we group those property names by the name of the entity set containing the entity type to which the property belongs using these two functions:&lt;/p&gt;

&lt;div id="codeSnippetWrapper"&gt;
  &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"&gt;&lt;span style="color: #0000ff"&gt;string&lt;/span&gt; entitySetName(XElement entityType, XElement csdl, XNamespace edm)&lt;br /&gt;{&lt;br /&gt;    &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; (from set &lt;span style="color: #0000ff"&gt;in&lt;/span&gt; csdl.Element(edm + &lt;span style="color: #006080"&gt;&amp;quot;EntityContainer&amp;quot;&lt;/span&gt;)&lt;br /&gt;                            .Elements(edm + &lt;span style="color: #006080"&gt;&amp;quot;EntitySet&amp;quot;&lt;/span&gt;)&lt;br /&gt;            &lt;span style="color: #0000ff"&gt;where&lt;/span&gt; entityTypeName(set) == entityType.Attribute(&lt;span style="color: #006080"&gt;&amp;quot;Name&amp;quot;&lt;/span&gt;).Value&lt;br /&gt;            select (&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;)set.Attribute(&lt;span style="color: #006080"&gt;&amp;quot;Name&amp;quot;&lt;/span&gt;).Value).Single();&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;span style="color: #0000ff"&gt;string&lt;/span&gt; entityTypeName(XElement entitySet)&lt;br /&gt;{&lt;br /&gt;    XElement schema = entitySet.Parent.Parent;&lt;br /&gt;    &lt;span style="color: #0000ff"&gt;string&lt;/span&gt; nsPrefix = schema.Attribute(&lt;span style="color: #006080"&gt;&amp;quot;Namespace&amp;quot;&lt;/span&gt;).Value + &lt;span style="color: #006080"&gt;&amp;quot;.&amp;quot;&lt;/span&gt;;&lt;br /&gt;    &lt;span style="color: #0000ff"&gt;string&lt;/span&gt; aliasPrefix = schema.Attribute(&lt;span style="color: #006080"&gt;&amp;quot;Alias&amp;quot;&lt;/span&gt;).Value + &lt;span style="color: #006080"&gt;&amp;quot;.&amp;quot;&lt;/span&gt;;&lt;br /&gt;    &lt;span style="color: #0000ff"&gt;string&lt;/span&gt; typeName = ((&lt;span style="color: #0000ff"&gt;string&lt;/span&gt;)entitySet.Attribute(&lt;span style="color: #006080"&gt;&amp;quot;EntityType&amp;quot;&lt;/span&gt;).Value).Trim();&lt;br /&gt;&lt;br /&gt;    &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (typeName.StartsWith(nsPrefix))&lt;br /&gt;    {&lt;br /&gt;        &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; typeName.Substring(nsPrefix.Length);&lt;br /&gt;    }&lt;br /&gt;    &lt;span style="color: #0000ff"&gt;else&lt;/span&gt; &lt;span style="color: #0000ff"&gt;if&lt;/span&gt; (typeName.StartsWith(aliasPrefix))&lt;br /&gt;    {&lt;br /&gt;        &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; typeName.Substring(aliasPrefix.Length);&lt;br /&gt;    }&lt;br /&gt;    &lt;span style="color: #0000ff"&gt;else&lt;/span&gt;&lt;br /&gt;    {&lt;br /&gt;        &lt;span style="color: #0000ff"&gt;return&lt;/span&gt; &lt;span style="color: #006080"&gt;&amp;quot;UNEXPECTED TYPENAME -- Where is the namespace?&amp;quot;&lt;/span&gt;;&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;

  &lt;br /&gt;&lt;/div&gt;

&lt;p&gt;The result of this query is an IGrouping&amp;lt;string, string&amp;gt; where the first string is the name of the entity set and the second string is a collection of property names from the base type within that set.&amp;#160; With that information it’s a simple matter to load the SSDL into memory, search for the relevant entity types (in the case of the SSDL, each table is represented by an entity type and each column within the table is a property of that type) and properties within them.&amp;#160; Then we swap out the attributes on the XElement for that property and set the name, the type to rowversion and the store generated pattern to computed.&amp;#160; Finally, the template serializes the XML for the SSDL to its output.&lt;/p&gt;

&lt;h3&gt;&lt;/h3&gt;

&lt;h2&gt;&lt;/h2&gt;

&lt;h3&gt;But what about derived types?&lt;/h3&gt;

&lt;div&gt;The above algorithm is all well and good for a model with no inheritance—every entity’s corresponding SSDL can be fixed up properly, but what if I want to put a concurrency property on an inherited type?&amp;#160; As it turns out the EF doesn’t allow that; concurrency properties can only be present on the base type for an entity set.&amp;#160; While I generally don’t like limitations of any kind, I can’t really think of any scenario where I’d want a concurrency property only on a derived type, and if I do have them on a base type, then I don’t need a different or additional property on any of the derived types.&lt;/div&gt;

&lt;div&gt;&amp;#160;&lt;/div&gt;

&lt;div&gt;In fact, for standard TPH and TPC scenarios all of the properties for a particular entity instance appear in a single row of a single table.&amp;#160; With TPH all of the instances are in a single table, and in TPC there are multiple tables involved but each type has its own table with all of the properties both from the base type and added in the derived type in that table.&amp;#160; So the concurrency property will appear on each table and a rowversion will work just fine because any property changing in that row will cause the concurrency property to change.&lt;/div&gt;

&lt;div&gt;&amp;#160;&lt;/div&gt;

&lt;div&gt;I got to thinking about TPT, though, and became a little worried.&amp;#160; First off, TPT is the default inheritance strategy used by model first.&amp;#160; In this strategy the properties from a base type all live in one table which has a row for every single entity in the set, while extra properties added&amp;#160; by derived types are placed in their own tables with just those properties and the primary key.&amp;#160; So for example, if I have entity type A with an id, scalar properties a and b, and a version, and I have type B which inherits from A and adds scalar property c, then the database would have table A with columns for id, a, b and version PLUS table B with columns for id and c.&amp;#160; (A similar sort of case exists with entity splitting or mixed mode mapping, but it’s easier to think about the pure TPH, TPC and TPT scenarios.)&amp;#160; In this kind of mapping, what happens if I have an instance of type B and only property c is modified?&amp;#160; Then only table B needs an update, and the rowversion would not be updated since SQL Server only maintains it for changes to the row of the table where it resides.&amp;#160; Doh!&lt;/div&gt;

&lt;div&gt;&amp;#160;&lt;/div&gt;

&lt;div&gt;After banging my head against the wall for a little while, I decided to check with some folks on the team to see what might be done to solve this problem.&amp;#160; Could we relax the restriction on concurrency properties only being allowed in the base type (in which case maybe for TPT scenarios we could add a second concurrency property on each derived type which would track changes on the extra tables)?&amp;#160; As it turns out Colin Meek, one of the brightest guys I know and a key member of the team, was way ahead of me.&amp;#160; He was able to tell me that the design for the update code that handles concurrency checks already takes this condition into account, and whenever any part of an entity which has a concurrency token is modified, the update system of the EF guarantees that the table with the concurrency value is “touched”.&amp;#160; In cases where there isn’t a real modification being made, a fake update statement is issued which doesn’t really change anything but does force the rowversion to update.&lt;/div&gt;

&lt;div&gt;&amp;#160;&lt;/div&gt;

&lt;div&gt;So, in the end there was nothing to worry about.&amp;#160; The SSDL modification algorithm described above works just fine, and once the updated workflow XAML and template were put into place in the project, model first sales through cleanly and produces code which creates a database with rowversion properties for each entity type.&amp;#160; And the whole thing is verified by the successful completion of the unit test described in the first part of the article.&lt;/div&gt;

&lt;h3&gt;Conclusions&lt;/h3&gt;

&lt;div&gt;AppWeek has come and gone, and in the end I spent the whole week getting my one test to run, but we have that much more of a stable foundation for D3 work to build on.&amp;#160; In addition at least one key bug was found and fixed, and some extensibility scenarios were explored and opportunities for improvement identified.&amp;#160; The really good news, though, is that the EF in general is starting to become flexible enough that even if it doesn’t work out of the box in just the way I want, I can customize it for my needs.&lt;/div&gt;

&lt;div&gt;&amp;#160;&lt;/div&gt;

&lt;div&gt;- Danny&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9806444" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/dsimmons/archive/tags/Entity+Designer/default.aspx">Entity Designer</category><category domain="http://blogs.msdn.com/dsimmons/archive/tags/D3/default.aspx">D3</category></item><item><title>D3: Fun with Concurrency and Model First – Part 1</title><link>http://blogs.msdn.com/dsimmons/archive/2009/06/27/d3-fun-with-concurrency-and-model-first-part-1.aspx</link><pubDate>Sat, 27 Jun 2009 03:10:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9806127</guid><dc:creator>dsimmons@microsoft.com</dc:creator><slash:comments>0</slash:comments><comments>http://blogs.msdn.com/dsimmons/comments/9806127.aspx</comments><wfw:commentRss>http://blogs.msdn.com/dsimmons/commentrss.aspx?PostID=9806127</wfw:commentRss><description>&lt;P&gt;The second D3 release is now up at: &lt;A title="direct link" href="http://code.msdn.microsoft.com/Project/Download/FileDownload.aspx?ProjectName=d3&amp;amp;DownloadId=6342" mce_href="http://code.msdn.microsoft.com/Project/Download/FileDownload.aspx?ProjectName=d3&amp;amp;DownloadId=6342"&gt;d3-0.0026.zip&lt;/A&gt;&amp;nbsp; It’s the fruit of my labors pretty much full-time this week because it has been “App Week” on the EF team this week.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;&lt;A href="http://www.the-simmons.net/images/D3FunwithConcurrencyandModelFirst_E7DE/appweek.jpg" mce_href="http://www.the-simmons.net/images/D3FunwithConcurrencyandModelFirst_E7DE/appweek.jpg"&gt;&lt;IMG style="BORDER-BOTTOM: 0px; BORDER-LEFT: 0px; DISPLAY: block; FLOAT: none; MARGIN-LEFT: auto; BORDER-TOP: 0px; MARGIN-RIGHT: auto; BORDER-RIGHT: 0px" title=appweek border=0 alt=appweek src="http://www.the-simmons.net/images/D3FunwithConcurrencyandModelFirst_E7DE/appweek_thumb.jpg" width=495 height=484 mce_src="http://www.the-simmons.net/images/D3FunwithConcurrencyandModelFirst_E7DE/appweek_thumb.jpg"&gt;&lt;/A&gt; &lt;/P&gt;
&lt;P&gt;What a great time!&amp;nbsp; My kids got out of school for summer break&amp;nbsp;last Friday (which means I have the option of sleeping in rather than waking up early to drive the car pool), and this week I got to almost completely clear my calendar and spend time working on DPMud.&amp;nbsp; App week is a time we set aside periodically to devote as much of our attention as possible to using the EF and related technologies to build applications so that we can experience some of the joys (and pain) of our valued customers.&amp;nbsp; Most everyone looks forward to it, and we invariably find lots of great opportunities to improve the product.&lt;/P&gt;
&lt;P&gt;While most other folks have been building new applications from scratch, I devoted my week to concentrated time on my long-running favorite app and just picked the next task off my to-do list and went to work.&amp;nbsp; That task was to add a concurrency-token property to each of my entities and a simple test to verify that optimistic concurrency checks are working correctly.&amp;nbsp; Seems pretty simple right?&amp;nbsp; The model currently only has 4 entities, so how hard could it be?&amp;nbsp; Can you say “working all week on this one task”?&amp;nbsp; :-(&lt;/P&gt;
&lt;P&gt;I won’t claim to be a test-first kind of developer, and the test code below is something I wrote after I had things working rather than first, but I’ll show it to you first so you can capture the goal.&amp;nbsp; Then we’ll talk through the challenges I encountered and how I conquered them (in the hope that I can save you some pain).&amp;nbsp; If you remember from &lt;A href="http://blogs.msdn.com/dsimmons/archive/2009/06/11/d3-release-0-0010.aspx" mce_href="http://blogs.msdn.com/dsimmons/archive/2009/06/11/d3-release-0-0010.aspx"&gt;my post about the last release&lt;/A&gt;, each entity currently in the model has a similar set of scalar properties but different relationships.&amp;nbsp; My idea was to just add a Version property which would be marked as a concurrency token and setup to be automatically updated in the database any time any property on the entity changes so that we would get automatic concurrency checks.&amp;nbsp; This property should actually have protected visibility because I don’t want to interact with it directly when using my entities—I just want the EF to use it and maintain it for me.&amp;nbsp; The result would enable this test helper method:&lt;/P&gt;
&lt;DIV&gt;&lt;PRE style="BORDER-BOTTOM-STYLE: none; TEXT-ALIGN: left; PADDING-BOTTOM: 0px; LINE-HEIGHT: 12pt; BORDER-RIGHT-STYLE: none; BACKGROUND-COLOR: #f4f4f4; MARGIN: 0em; PADDING-LEFT: 0px; WIDTH: 100%; PADDING-RIGHT: 0px; FONT-FAMILY: 'Courier New', courier, monospace; DIRECTION: ltr; BORDER-TOP-STYLE: none; COLOR: black; FONT-SIZE: 8pt; BORDER-LEFT-STYLE: none; OVERFLOW: visible; PADDING-TOP: 0px" id=codeSnippet&gt;&lt;SPAN style="COLOR: #0000ff"&gt;private&lt;/SPAN&gt; &lt;SPAN style="COLOR: #0000ff"&gt;void&lt;/SPAN&gt; VerifyConcurrency&amp;lt;T&amp;gt;(Func&amp;lt;T&amp;gt; create, Action&amp;lt;T&amp;gt; modify) &lt;SPAN style="COLOR: #0000ff"&gt;where&lt;/SPAN&gt; T : &lt;SPAN style="COLOR: #0000ff"&gt;class&lt;/SPAN&gt;&lt;BR&gt;{&lt;BR&gt;    &lt;SPAN style="COLOR: #0000ff"&gt;using&lt;/SPAN&gt; (var ctx = Utilities.CreateTestContext())&lt;BR&gt;    {&lt;BR&gt;        var objectSet = ctx.CreateObjectSet&amp;lt;T&amp;gt;();&lt;BR&gt;        var obj = create();&lt;BR&gt;        objectSet.AddObject(obj);&lt;BR&gt;        ctx.SaveChanges();&lt;BR&gt;&lt;BR&gt;        &lt;SPAN style="COLOR: #0000ff"&gt;using&lt;/SPAN&gt; (var ctx2 = Utilities.CreateTestContext())&lt;BR&gt;        {&lt;BR&gt;            var key = ctx.ObjectStateManager.GetObjectStateEntry(obj).EntityKey;&lt;BR&gt;            var obj2 = (T)ctx2.GetObjectByKey(key);&lt;BR&gt;            modify(obj2);&lt;BR&gt;            ctx2.SaveChanges();&lt;BR&gt;        }&lt;BR&gt;&lt;BR&gt;        modify(obj);&lt;BR&gt;        ctx.SaveChanges();&lt;BR&gt;    }&lt;BR&gt;}&lt;/PRE&gt;&lt;/DIV&gt;
&lt;DIV&gt;&amp;nbsp;&lt;/DIV&gt;
&lt;DIV&gt;I made the method generic and gave it two delegate parameters so that I can easily re-use it for each entity type I currently have plus extend it as I add more types over time.&amp;nbsp; I also designed the code so that it will work with POCO types since I anticipate switching D3 to use POCO classes in the near future.&amp;nbsp; As a part of this release I also introduced a simple utility method which creates the D3Context with a connection string to my little test database—this way it’s quick and easy to type since intellisense finds things for me.&lt;/DIV&gt;
&lt;DIV&gt;&amp;nbsp;&lt;/DIV&gt;
&lt;DIV&gt;The basic pattern in this method is that it uses one context to add an entity to the database.&amp;nbsp; I use the create delegate because different entities have different requirements as far as what must be set on them to make them persist successfully.&amp;nbsp; Each of our current entity types requires a non-null Name property, for instance, but while the Room entity doesn’t have any other required properties, an Actor must have a non-null Room reference, etc.&amp;nbsp; &lt;/DIV&gt;
&lt;DIV&gt;&amp;nbsp;&lt;/DIV&gt;
&lt;DIV&gt;Once the new entity is added, I then create another context instance (which means another connection to the DB, etc.) and on it retrieve another copy of that same entity.&amp;nbsp; I do this retrieval by having the state manager in the first context lookup the entity for me by reference (works for POCO) and then give me back the EntityKey corresponding to it (also works for POCO even though the entity itself doesn’t have an EntityKey property).&amp;nbsp; Then I can use that key with the second context to load another copy of the entity, and call the modify delegate which makes a unique update to some property on the entity and saves that update to the database.&lt;/DIV&gt;
&lt;DIV&gt;&amp;nbsp;&lt;/DIV&gt;
&lt;DIV&gt;At this point the first instance of the entity is being tracked by the first context, and it’s concurrency token (assuming everything is configured correctly) represents the state of the entity before the second context updated anything.&amp;nbsp; So we call the modify delegate on this entity and SaveChanges which throws an OptimisticConcurrencyException because the concurrency token in the database doesn’t match what’s in this context.&lt;/DIV&gt;
&lt;DIV&gt;&amp;nbsp;&lt;/DIV&gt;
&lt;DIV&gt;In the actual test, I create a list of Action types which call this method specifying the appropriate type and passing in lambdas for the create and modify delegates.&amp;nbsp; Then it just loops over that list running the action and verifying that each call produces the appropriate exception.&amp;nbsp; You can look at the file Tests\Concurrency.cs in the release if you want the full details.&amp;nbsp; &lt;/DIV&gt;
&lt;DIV&gt;&amp;nbsp;&lt;/DIV&gt;
&lt;DIV&gt;The point of all this, though, is that to make this test pass I needed my entities to have concurrency properties that were configured properly in the database.&amp;nbsp; With recent versions of SQL Server, the best way to accomplish that is with a &lt;A href="http://www.the-simmons.net/images/D3FunwithConcurrencyandModelFirst_E7DE/ConcurrencyProperty.jpg" mce_href="http://www.the-simmons.net/images/D3FunwithConcurrencyandModelFirst_E7DE/ConcurrencyProperty.jpg"&gt;&lt;IMG style="BORDER-BOTTOM: 0px; BORDER-LEFT: 0px; DISPLAY: inline; MARGIN-LEFT: 0px; BORDER-TOP: 0px; MARGIN-RIGHT: 0px; BORDER-RIGHT: 0px" title=ConcurrencyProperty border=0 alt=ConcurrencyProperty align=right src="http://www.the-simmons.net/images/D3FunwithConcurrencyandModelFirst_E7DE/ConcurrencyProperty_thumb.jpg" width=280 height=392 mce_src="http://www.the-simmons.net/images/D3FunwithConcurrencyandModelFirst_E7DE/ConcurrencyProperty_thumb.jpg"&gt;&lt;/A&gt;RowVersion column (previously called a timestamp).&amp;nbsp; This special column type is stored as an 8 byte binary, and the server guarantees that it will have a unique value any time any part of a row in its table is modified.&amp;nbsp; The trick is that this special type only exists in the server—it’s not available in the CLR or the EDM conceptual model.&amp;nbsp; If I were reverse engineering a model from the database, that would be no big deal.&amp;nbsp; The tools would automatically map the RowVersion column in the database to an 8 byte binary property in my model.&amp;nbsp; In this case, though, I’m using model first to generate the database from my model, and when I create the property, model first has no way to know that it should create a RowVersion type rather than a binary type in the DB.&lt;/DIV&gt;
&lt;P&gt;So it was time to customize the model first process again, but before I got even that far I ran into a bug.&amp;nbsp; Ahhh…&amp;nbsp; The joy of AppWeek and of beta software.&amp;nbsp; The issue is that if you set Concurrency Mode to Fixed on any of your entities in VS 2010 beta 1, then when you choose Generate Database Script from Model, the tool will display an error rather than generating the script.&amp;nbsp; Considerable debugging and discussion with the developer who did most all of the work for model first later, we were able to track the problem down to a one line problem where model first was assuming that all property facets that could be set in the conceptual model were at least valid possibilities for the storage model, when in fact Concurrency Mode is the one property which can only be in the conceptual model and not the storage model.&amp;nbsp; So the workflow activity that generates the SSDL from the CSDL was triggering an exception from the metadata system.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;This bug will be fixed in beta 2, but that doesn’t help us much for D3 right now.&amp;nbsp; So my final solution was to extract a small piece of the model-first workflow into a separate DLL, make a fix to the code and then modify the DbGen.xaml file which describes the workflow to call out to that DLL rather than the core version that ships with the product.&amp;nbsp; The final result is part of this release, and it’s called modelfirst-bugfix.dll.&amp;nbsp; If you go the misc directory under the release and run the batch file install-bugfix.cmd it will copy the DLL to a directory in your VS installation (make sure you run this from a VS command prompt where the DevEnvDir environment variable is set).&amp;nbsp; Naturally this little hack is completely unsupported, but it works for me, and it might work for you too if you need to use model first with concurrency and beta 1 of EF4.&lt;/P&gt;
&lt;P&gt;Now at least I can run model first when I have concurrency configured, but I’ve still got the problem that my properties come through as binary rather than RowVersion type in the DB.&amp;nbsp; That’s where I’ll pick up the next post…&amp;nbsp; Until then, happy coding.&lt;/P&gt;
&lt;P&gt;- Danny&lt;/P&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9806127" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/dsimmons/archive/tags/Entity+Framework/default.aspx">Entity Framework</category><category domain="http://blogs.msdn.com/dsimmons/archive/tags/D3/default.aspx">D3</category></item><item><title>D3: Release 0.0010</title><link>http://blogs.msdn.com/dsimmons/archive/2009/06/11/d3-release-0-0010.aspx</link><pubDate>Thu, 11 Jun 2009 02:22:57 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9725285</guid><dc:creator>dsimmons@microsoft.com</dc:creator><slash:comments>1</slash:comments><comments>http://blogs.msdn.com/dsimmons/comments/9725285.aspx</comments><wfw:commentRss>http://blogs.msdn.com/dsimmons/commentrss.aspx?PostID=9725285</wfw:commentRss><description>&lt;p&gt;OK folks, after way too much delay, I’ve finally gotten all my ducks in a row and begun the process of rewriting DPMud.&amp;#160; Since my goal is to completely rebuild it from scratch, the process is going to take a while, and I intend to let you all look over my shoulder a bit as I go.&amp;#160; So don’t expect too much from this first release—all we have is a basic solution with a very simple model and some unit tests.&amp;#160; You can download the release from: &lt;a title="d3-0.0010" href="http://code.msdn.microsoft.com/d3/Release/ProjectReleases.aspx?ReleaseId=2815"&gt;d3-0.0010&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;First, let’s take a look at a few decisions that came up along the way, and then we’ll dig into some specific code areas.&lt;/p&gt;  &lt;h3&gt;&lt;/h3&gt;  &lt;h3&gt;Decisions&lt;/h3&gt;  &lt;ul&gt;   &lt;li&gt;&lt;strong&gt;Source Control and Licensing&lt;/strong&gt;: It is very important to me to make this project as relevant and useful as possible for folks trying to build applications using the EF.&amp;#160; So we decided to release the code via MS-PL which is a very permissive license.&amp;#160; I’m no lawyer, but my understanding is that this basically means you can copy the source and use any part or all of it in your own projects.&amp;#160; Originally it was my hope that I could just put the project on codeplex and use it for source control so that anyone interested could enlist and just sync down changes to their local machine as the project progresses, but there were various hang-ups with this approach, and in the end I decided to just use local source control and then periodically push releases up to code gallery which has a simple site system and where everything is automatically licensed with MS-PL.       &lt;br /&gt;&amp;#160; &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;Version Numbers&lt;/strong&gt;: One of those mundane but required decisions along the way is how we will create version numbers for the releases.&amp;#160; Here’s what I decided: Until we have the thing up and running, everything is version 0.something.&amp;#160; The last four digits of the version are in the form MMDD where MM is the number of months since I started releasing (so 00 is June ‘09), and DD is the day of the month for that release.&amp;#160; I haven’t done it yet, but that allows me to have a very simple algorithm to automate version stamping and such as I make subsequent releases.       &lt;br /&gt;&amp;#160; &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;EF Versions and Dependencies&lt;/strong&gt;: One critical area of decisions was around what EF features do I take dependencies on—particularly when we’re in the state where EF4 is not yet complete.&amp;#160; In the end I decided that the main principle was to avoid taking dependencies on EF features that aren’t yet available outside the team so that you can stay up with me if you like.&amp;#160; This means, for instance, that I’m not going to take a dependency on foreign-key support even though I have access to an internal build where it’s working great.&amp;#160; When FKs are publically available, we’ll take a look at the project at that point and evaluate whether or not it’s worthwhile to refactor the app to take advantage of them (almost certainly we will do that refactoring).&amp;#160; Similarly, I’m not yet going to take a dependency on self-tracking entities because it isn’t yet available.&amp;#160; It will become available much sooner than FKs, though, so I will plan on taking advantage of it soon.&amp;#160; A harder question was code-only.&amp;#160; The first CTP of it will also be available soon (in the same download with self-tracking entities), but I already know of some areas where I’ll need more control over the model and database generation than code-only will support in its first CTP, so we’ll have to wait on that refactoring until a later CTP of code-only.&amp;#160; So the basic approach will be to use EF4 beta 1 with model-first to make it efficient to design the model and generate the database and code from that model. &lt;/li&gt; &lt;/ul&gt;  &lt;h3&gt;Initial Model&lt;/h3&gt;  &lt;p&gt;Like every other part of the system, we’re going to start with a simple model and expand.&amp;#160; Here’s a first look:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://www.the-simmons.net/images/D3Release0.0010_AFC1/D3ModelDiagram.jpg"&gt;&lt;img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="D3ModelDiagram" border="0" alt="D3ModelDiagram" src="http://www.the-simmons.net/images/D3Release0.0010_AFC1/D3ModelDiagram_thumb.jpg" width="475" height="509" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;A few things to notice: &lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Each entity has an Id property which is a server-generated integer.&amp;#160;&amp;#160; &lt;br /&gt;&amp;#160; &lt;/li&gt;    &lt;li&gt;Each of these entities is a “real” thing which players will interact with in the virtual environment of the game, and as such we have given them all a few common properties including Name and Description.&amp;#160; Eventually we’ll define an interface for these common properties so that we can reason about the commonality of these objects.&amp;#160; We could have an abstract base class for each of these entities, but we want them each in their own entity sets, and the designer doesn’t support more than one entityset with the same base type, so using an interface gets the key aspects we want while allowing us to still use the designer (we don’t really need implementation inheritance here anyway).      &lt;br /&gt;&amp;#160; &lt;/li&gt;    &lt;li&gt;The two associations between Room and Exit have each had one of the navigation properties removed so that Room only has one collection of “Exits” (it doesn’t also have a collection of entrances, so to speak), and Exit has only the TargetRoom navigation property.&amp;#160; This makes our entities follow the intended model where exits go only one way.&amp;#160; If you want two rooms to be connected in a symmetrical fashion, you need two exits one going from room A to room B, and another one going back from room B to room A.&amp;#160; This is important because it means that we can easily give different names to the exits (from room A you go East to room B, but from room B you have to go West to get back to room A), and it means that you don’t always have symmetrical paths (when you jump off a cliff you can’t necessarily get back to the top of the cliff using the same way you got down, etc.).      &lt;br /&gt;&amp;#160; &lt;/li&gt;    &lt;li&gt;We don’t yet have version fields for concurrency checking.&amp;#160; That will come later, because it requires some additional customization to the database generation.      &lt;br /&gt;&amp;#160; &lt;/li&gt;    &lt;li&gt;Item has a relationship with Actor and one with Room, but logically an item can only be related to one of them at a time (and it must always be related to one or the other so that items have location).&amp;#160; These constraints we will represent in the database rather than the conceptual model.&amp;#160; They aren’t currently enforced, but they will be once we make additional customizations to database generation. &lt;/li&gt; &lt;/ul&gt;  &lt;h3&gt;Customizing “Model First”&lt;/h3&gt;  &lt;p&gt;The feature we call model first shows up in the entity designer (aka Escher) as the option “Generate Database Script from Model” on the context menu when you right click on an open part of the designer surface.&amp;#160; Out of the box this will generate a SQL DDL script that you can use to create a database for persisting the entities in your model.&amp;#160; It also automatically generates the SSDL and MSL which corresponds to that model.&amp;#160; This is great because it means that I can concentrate on the thing that is important to my program, the conceptual model.&amp;#160; If I make a change to the model, once that change is complete, I’m done.&amp;#160; I don’t have to also modify the database and the mapping to reflect that change.&amp;#160; Since I’m also generating entity classes from the model, I get a nice “DRY” (Don’t Repeat Yourself) development experience even though various parts of the system do have repetition, I don’t have to engage in that repetition myself.&amp;#160; Naturally we want to have an even more DRY experience, and code-first will lead us there for folks who want to do everything in code, but for the design-time experience this is not half bad.&lt;/p&gt;  &lt;p&gt;Naturally, though, there are times where I want more control over the database generation process, which is why there are customization hooks built-in.&amp;#160; The process of generating the database is orchestrated by a customizable workflow which has a couple of activities that manage generating an MSL and SSDL for the CSDL and then generating SQL from that SSDL.&amp;#160; This second step (SSDL-&amp;gt;SQL) is further customizable because it is accomplished with a T4 template.&amp;#160;&amp;#160; Eventually we will take advantage of these customization mechanisms to allow us to automatically generate rowversion columns for concurrency, constraints that keep item relationships straight and other things.&lt;/p&gt;  &lt;p&gt;All of this seemed somewhat academic, though, for the first few phases of the project until I started thinking through my testing strategy.&amp;#160; Eventually we’ll test parts of the system using fakes and mocks and the like, but we also need integration tests that send data all the way down to the database and back, and I wanted to start writing those tests right away and deliver them with my initial stab at the model.&amp;#160; To make that work I really wanted APIs for creating and dropping the database somewhat like we can get from L2S so that my tests can create a temp version of the database (separate storage but same schema) and test pushing data in and out of it.&amp;#160; Eventually this will also be useful for deployment, import/export of data, version-to-version upgrades and the like.&lt;/p&gt;  &lt;p&gt;So, I decided to customize the db generation process now by modifying the SSDL-&amp;gt;SQL template to generate a C# method for creating the database schema rather than a SQL script.&amp;#160; The process to set things up for customization looks like this:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Copy the workflow xaml file from %ProgramFiles\Microsoft Visual Studio 10.0\Extensions\EntityFrameworkTools\Workflows\DbGen.xaml and the SQL gen template from %ProgramFiles\Microsoft Visual Studio 10.0\Extensions\EntityFrameworkTools\Templates\SsdlToSql10.tt to my project.&amp;#160; &lt;/li&gt;    &lt;li&gt;I renamed the template to SsdlToCode.tt and modified the xaml file’s TemplatePath to just have that name rather than the full path to the original template.&amp;#160; &lt;/li&gt;    &lt;li&gt;Both files I added to my project in VS, but because they aren’t actually used at compile time (they are just used by the designer when I choose the menu option to generate the database) I made sure that the Custom Tool property for each of them is blank and the Build Action property is set to None. &lt;/li&gt;    &lt;li&gt;I clicked on a blank part of the Entity Designer surface and then set the “Generate Database Script Workflow” property to just DbGen.xaml (just the file name because the xaml file is in the same project and directory with the EDMX). &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;Now when I choose the option to generate the database it runs the workflow as specified in my project which then uses the template from my project rather than the default versions.&lt;/p&gt;  &lt;p&gt;Next, I modified the template file to output C# code rather than SQL.&amp;#160; You can find the template file in the release and do your own diff against the default template, but the basic approach was to wrap each batch of SQL statements up to a “GO” in an ado.net command with a C# @”” string and execute it.&amp;#160; I eliminated a chunk of the template that would drop existing tables because my approach is to drop the whole database and recreate it, and I put all of these execute statements into a method on an internal partial class that I added to my model DLL.&amp;#160; That way most of that class is defined outside the template but this one method can be defined by the code generated from the template.&amp;#160; Then I further created a partial class file for my generated EF context and added methods to check for existence of the database, drop the database, and create it (using the generated method).&lt;/p&gt;  &lt;p&gt;One current limitation in the designer is that the generate database command always by default creates a file with a name based on the name of the EDMX file and with SQL for the extension.&amp;#160; I’ve already started discussions with the designer folks about adding some customization hooks here, but for now you just have to remember that whenever you generate the database you should rename the file.&lt;/p&gt;  &lt;p&gt;All of this enabled me to write the following simple test:&lt;/p&gt;  &lt;div&gt;   &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"&gt;[TestMethod]&lt;br /&gt;&lt;span style="color: #0000ff"&gt;public&lt;/span&gt; &lt;span style="color: #0000ff"&gt;void&lt;/span&gt; DropAndCreate()&lt;br /&gt;{&lt;br /&gt;    &lt;span style="color: #0000ff"&gt;using&lt;/span&gt; (var ctx = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; D3Context(&lt;span style="color: #006080"&gt;&amp;quot;name=D3TestContext&amp;quot;&lt;/span&gt;))&lt;br /&gt;    {&lt;br /&gt;        ctx.DropDatabase();&lt;br /&gt;        Assert.IsFalse(ctx.DatabaseExists());&lt;br /&gt;        ctx.CreateDatabase();&lt;br /&gt;        Assert.IsTrue(ctx.DatabaseExists());&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;
&lt;/div&gt;

&lt;div&gt;&amp;#160;&lt;/div&gt;

&lt;div&gt;Not only is it simple to perform these operations, but also everything is based on the connection string given.&amp;#160; So I just created two different connection strings in my app.config file—one called D3Context (the default) and the D3TestContext which is the exact same as the other except that it has a different initial-catalog name for my test database.&lt;/div&gt;

&lt;div&gt;&amp;#160;&lt;/div&gt;

&lt;h3&gt;The SqlDb Internal Class&lt;/h3&gt;

&lt;div&gt;It’s probably also worthwhile to take a brief look at the internal class I called SqlDb which does the heavy lifting for these database interactions.&amp;#160; The first interesting piece of the puzzle is that in order to create or drop the database with SQL Server (or in this case Sql Express) we need to make sure that we don’t use a connection string with the database in question as the initial-catalog.&amp;#160; So, we extract the connection string from the StoreConnection property on the EntityClient connection instance created by the context and create a SqlConnectionBuilder from it.&amp;#160; SqlDb’s constructor takes a DbConnection parameter since that’s what ObjectContext exposes and creates the builder like this:&lt;/div&gt;

&lt;div&gt;&amp;#160;&lt;/div&gt;

&lt;div id="codeSnippetWrapper"&gt;
  &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"&gt;var builder = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; SqlConnectionStringBuilder(((EntityConnection)entityConnection).StoreConnection.ConnectionString);&lt;/pre&gt;

  &lt;br /&gt;&lt;/div&gt;

&lt;p&gt;Then we store the initial-catalog property into a string field so we know the name of the database we should be working with, and then we replace the initial-catalog with “master” since that database is present on every SQL instance.&lt;/p&gt;

&lt;p&gt;The constructor then extracts the new connection string from the builder and uses it to create a new SqlConnection instance.&amp;#160; We use this connection to execute commands without directly connecting to the database.&amp;#160; The class also implements IDisposable so that its Dispose method can Dispose of the SqlConnection.&lt;/p&gt;

&lt;p&gt;The other interesting trick which came up was the fact that while my initial executions of the above test succeeded while stepping through in the debugger, running the whole test straight through failed because the first part of the DropDatabase method executes a command to check if the database exists, and after that the drop command would fail with an error saying that the database was in use.&amp;#160; Eventually I fixed this by adding a ClearAllPools method to the class which closes the connection, calls SqlClient.ClearAllPools() to make sure that there are no connections in the connection pool holding onto the database and then re-opens the connection.&amp;#160; This method is called after the existence check and before the command to drop the database.&lt;/p&gt;

&lt;h3&gt;Conclusions&lt;/h3&gt;

&lt;p&gt;We’re finally off and running!&amp;#160; We have an initial model, a simple way to deploy the database and some initial tests.&amp;#160; (Those tests have already found a couple of issues I had in my first crack at the model, by the way.&amp;#160; So the testing is already paying off.&amp;#160; Yay!)&amp;#160; Next I’ll probably tackle some further customizations of the generated database.&amp;#160; Soon we’ll look at replacing the default code gen with a POCO template, and in the not distant future I hope to fill out more pieces of the architecture so we can get a small end-to-end slice going with a WCF service and Silverlight, but all in good time…&lt;/p&gt;

&lt;p&gt;- Danny 
  &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9725285" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/dsimmons/archive/tags/Entity+Framework/default.aspx">Entity Framework</category><category domain="http://blogs.msdn.com/dsimmons/archive/tags/D3/default.aspx">D3</category></item><item><title>Links: EF4 Podcast, N-Tier Anti-Patterns, and some thoughts about DDD</title><link>http://blogs.msdn.com/dsimmons/archive/2009/06/03/links-ef4-podcast-n-tier-anti-patterns-and-some-thoughts-about-ddd.aspx</link><pubDate>Wed, 03 Jun 2009 10:56:50 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9689907</guid><dc:creator>dsimmons@microsoft.com</dc:creator><slash:comments>1</slash:comments><comments>http://blogs.msdn.com/dsimmons/comments/9689907.aspx</comments><wfw:commentRss>http://blogs.msdn.com/dsimmons/commentrss.aspx?PostID=9689907</wfw:commentRss><description>&lt;p&gt;Here are a few more resources I hope you will find useful:&lt;/p&gt;  &lt;p&gt;Recently I had a conversation about EF4 with Carl and Richard of .Net Rocks, and it went up on their site today.&amp;#160; Have a listen at &lt;a title="http://www.dotnetrocks.com/default.aspx?showNum=451" href="http://www.dotnetrocks.com/default.aspx?showNum=451"&gt;http://www.dotnetrocks.com/default.aspx?showNum=451&lt;/a&gt;.&amp;#160; &lt;/p&gt;  &lt;p&gt;In addition, I have an &lt;a href="http://msdn.microsoft.com/en-us/magazine/dd882522.aspx"&gt;article about design/architecture decisions related to n-tier applications in the latest issue of MSDN Magazine&lt;/a&gt;.&amp;#160; This article is actually the first part of a two-part series.&amp;#160; Originally it was a single longer article that wasn’t so depressing as this one came out (all about what *not* to do without really giving any help on what you should do).&amp;#160; There are some important concepts, though, so hopefully you’ll find something useful even in this first part.&lt;/p&gt;  &lt;p&gt;At the same time that I’ve been busy with these, some other folks have been trying out the beta of EF4 and some very interesting posts are starting to appear like this &lt;a href="http://blog.keithpatton.com/2009/05/30/Entity+Framework+POCO+Repository+Using+Visual+Studio+2010+Net+40+Beta+1.aspx"&gt;dive into producing a POCO repository with the EF&lt;/a&gt; by Keith Patton and a great discussion of &lt;a href="http://blogs.rev-net.com/ddewinter/2009/05/31/linq-expression-trees-and-the-specification-pattern/"&gt;LINQ Expression Trees and the Specification Pattern&lt;/a&gt; by the EF team’s own David DeWinter.&lt;/p&gt;  &lt;p&gt;- Danny&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9689907" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/dsimmons/archive/tags/Entity+Framework/default.aspx">Entity Framework</category><category domain="http://blogs.msdn.com/dsimmons/archive/tags/DDD/default.aspx">DDD</category><category domain="http://blogs.msdn.com/dsimmons/archive/tags/Web+Services/default.aspx">Web Services</category></item><item><title>Some Great EF Resources</title><link>http://blogs.msdn.com/dsimmons/archive/2009/05/26/some-great-ef-resources.aspx</link><pubDate>Tue, 26 May 2009 02:33:57 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9640946</guid><dc:creator>dsimmons@microsoft.com</dc:creator><slash:comments>2</slash:comments><comments>http://blogs.msdn.com/dsimmons/comments/9640946.aspx</comments><wfw:commentRss>http://blogs.msdn.com/dsimmons/commentrss.aspx?PostID=9640946</wfw:commentRss><description>&lt;p&gt;One of the things that’s cool about working on the EF team and getting the chance to talk to customers about what we do and answer questions and such is that I get to hear about lots of things that folks outside the EF team do with the EF.&amp;#160; It’s especially neat when folks tell me about books, tools and other resources which help folks get more out of the EF or related technologies.&amp;#160; Unfortunately I’m often so buried under various responsibilities that I don’t always share these great resources as quickly as I should.&amp;#160; I also try to make sure that I give things a look over before I share them so that what I point you to are only the best, most valuable things which of course means that it takes even longer…&amp;#160; Sigh.&lt;/p&gt;  &lt;p&gt;The only reason I’m wasting your time with all the apologies today, is that I have three particularly good resources which I’m way overdue sharing.&amp;#160; I assure you (and the creators of these resources) that the delay has nothing to do with their quality.&amp;#160; If you haven’t seen these things, I highly recommend you check them out.&lt;/p&gt;  &lt;p&gt;The first one is Julie Lerman’s book, &lt;u&gt;&lt;a href="http://oreilly.com/catalog/9780596520281/"&gt;Programming Entity Framework&lt;/a&gt;&lt;/u&gt;.&amp;#160; Julie’s tireless efforts on behalf of the EF and its users hit a new height with the release of this book.&amp;#160; There’s an incredible volume of material covering all parts of the first release of the EF, and all samples are written in both C# and VB.Net.&lt;/p&gt;  &lt;p&gt;Next is the product of the Swiss MSDN team which put together a &lt;a href="http://blogs.msdn.com/swiss_dpe_team/archive/2008/10/27/ado-net-entity-framework-hands-on-lab.aspx"&gt;hand’s on lab for learning about the EF&lt;/a&gt; and even building an n-tier application using it.&amp;#160; It’s all done using the first release of the EF (.net 3.5 sp1) so it doesn’t take advantage of the new features we have added in EF4 beta1, but it will help you learn the fundamentals, and if you are working on an application using the EF which must deploy before EF4 releases, then it will be an especially useful tool.&lt;/p&gt;  &lt;p&gt;Finally, I’ve done some blogging about T4 and how you can use it to customize EF code generation in the first release.&amp;#160; In addition you may have heard that EF4 uses T4 not only for all the built-in code generation but also for database generation.&amp;#160; So learning to work with T4 is a good idea for anyone programming with the EF.&amp;#160; Unfortunately, though, VS doesn’t have great built-in support for editing T4 templates.&amp;#160; You can edit in VS, but it just treats them as a basic text file with no syntax coloring or intellisense support.&amp;#160; Hopefully that will be fixed in a future release of VS, but in the meantime there are two companies which have released T4 editors that plug into VS which make the experience of working with T4 much more pleasant.&amp;#160; Check out Clarius Consulting’s &lt;a href="http://www.visualt4.com/"&gt;Visual T4&lt;/a&gt; and Tangible Engineering’s &lt;a href="http://t4-editor.tangible-engineering.com/T4-Editor-Visual-T4-Editing.html"&gt;T4 Editor&lt;/a&gt;.&amp;#160; Particularly interesting is the fact that Tangible’s editor already has a version which works with VS 2010 beta 1, and you can download and install it from the extension manager within VS 2010.&lt;/p&gt;  &lt;p&gt;If you give these a try, I’d love to hear about your experiences with them, and if you know of something else which makes it better or easier to work with the EF, I’m always looking for information about those things as well.&lt;/p&gt;  &lt;p&gt;- Danny&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9640946" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/dsimmons/archive/tags/Entity+Framework/default.aspx">Entity Framework</category></item><item><title>EF4 beta 1 Forums &amp; Docs</title><link>http://blogs.msdn.com/dsimmons/archive/2009/05/20/ef4-beta-1-forums-docs.aspx</link><pubDate>Wed, 20 May 2009 22:02:56 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9632714</guid><dc:creator>dsimmons@microsoft.com</dc:creator><slash:comments>1</slash:comments><comments>http://blogs.msdn.com/dsimmons/comments/9632714.aspx</comments><wfw:commentRss>http://blogs.msdn.com/dsimmons/commentrss.aspx?PostID=9632714</wfw:commentRss><description>&lt;p&gt;Should have included this info in the last post, but better late than never.&amp;#160; &lt;/p&gt;  &lt;p&gt;If you have questions about EF4 beta 1, the place to ask is the EF4 pre-release forum:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a title="http://social.msdn.microsoft.com/Forums/en-US/adonetefx/threads" href="http://social.msdn.microsoft.com/Forums/en-US/adonetefx/threads"&gt;http://social.msdn.microsoft.com/Forums/en-US/adonetefx/threads&lt;/a&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;If you are looking for the documentation, then you’ll be interested in this link to the MSDN online docs.&amp;#160; For beta 1 docs are only available online, but they will be available both online and offline by the time the EF4 &amp;amp; VS2010 ships.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a title="http://msdn.microsoft.com/en-us/library/bb399572(VS.100).aspx" href="http://msdn.microsoft.com/en-us/library/bb399572(VS.100).aspx"&gt;http://msdn.microsoft.com/en-us/library/bb399572(VS.100).aspx&lt;/a&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt; - Danny&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9632714" width="1" height="1"&gt;</description></item><item><title>EF4 Beta 1 now available!</title><link>http://blogs.msdn.com/dsimmons/archive/2009/05/20/ef4-beta-1-now-available.aspx</link><pubDate>Wed, 20 May 2009 21:21:40 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9632651</guid><dc:creator>dsimmons@microsoft.com</dc:creator><slash:comments>1</slash:comments><comments>http://blogs.msdn.com/dsimmons/comments/9632651.aspx</comments><wfw:commentRss>http://blogs.msdn.com/dsimmons/commentrss.aspx?PostID=9632651</wfw:commentRss><description>&lt;p&gt;In case you haven’t heard yet, VS 2010 beta 1 and .Net 4 beta 1 are now available for public download, and that means EF4 beta 1 is available as well:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a title="http://msdn.microsoft.com/en-us/vstudio/dd582936.aspx" href="http://msdn.microsoft.com/en-us/vstudio/dd582936.aspx"&gt;http://msdn.microsoft.com/en-us/vstudio/dd582936.aspx&lt;/a&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Lots of goodies!&amp;#160; Check it out, and let us know what you think.&lt;/p&gt;  &lt;p&gt;- Danny&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9632651" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/dsimmons/archive/tags/Entity+Framework/default.aspx">Entity Framework</category></item><item><title>Online TechTalk about POCO and other EF4 Features</title><link>http://blogs.msdn.com/dsimmons/archive/2009/05/15/online-techtalk-about-poco-and-other-ef4-features.aspx</link><pubDate>Fri, 15 May 2009 09:47:31 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9617892</guid><dc:creator>dsimmons@microsoft.com</dc:creator><slash:comments>3</slash:comments><comments>http://blogs.msdn.com/dsimmons/comments/9617892.aspx</comments><wfw:commentRss>http://blogs.msdn.com/dsimmons/commentrss.aspx?PostID=9617892</wfw:commentRss><description>&lt;p&gt;Yesterday, while we were here at TechEd, Alex James and I sat down and recorded a short discussion about POCO and other features coming EF4.&amp;#160; Check it out at: &lt;a title="http://www.msteched.com/online/view.aspx?tid=ef76e96c-7471-44a6-aa88-1ada037471ca" href="http://www.msteched.com/online/view.aspx?tid=ef76e96c-7471-44a6-aa88-1ada037471ca"&gt;http://www.msteched.com/online/view.aspx?tid=ef76e96c-7471-44a6-aa88-1ada037471ca&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;- Danny&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9617892" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/dsimmons/archive/tags/Entity+Framework/default.aspx">Entity Framework</category></item><item><title>Code Sample from my Applied Entity Framework talk at TechEd 2009 now available</title><link>http://blogs.msdn.com/dsimmons/archive/2009/05/15/code-sample-from-my-applied-entity-framework-talk-at-teched-2009-now-available.aspx</link><pubDate>Fri, 15 May 2009 08:51:14 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9617786</guid><dc:creator>dsimmons@microsoft.com</dc:creator><slash:comments>2</slash:comments><comments>http://blogs.msdn.com/dsimmons/comments/9617786.aspx</comments><wfw:commentRss>http://blogs.msdn.com/dsimmons/commentrss.aspx?PostID=9617786</wfw:commentRss><description>&lt;p&gt;This week I gave a talk at TechEd focusing on architectural considerations as well as some useful tips for creating n-tier applications with the Entity Framework v3.5SP1.&amp;#160; The code from the simple sample application is now available at &lt;a title="http://code.msdn.microsoft.com/dtl401sample/" href="http://code.msdn.microsoft.com/dtl401sample/"&gt;http://code.msdn.microsoft.com/dtl401sample/&lt;/a&gt;.&amp;#160; It includes:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;an Entity Framework-based Business Object and DAL&lt;/li&gt;    &lt;li&gt;some rudimentary validation implemented using a T4-template to create customized code generation with an OnValidate partial method much like is available from LINQ to SQL&lt;/li&gt;    &lt;li&gt;a repository which abstracts the UI from data access &amp;amp; a fake implementation of that repository&lt;/li&gt;    &lt;li&gt;an asp.net MVC-based UI with URL routing that allows you to specify either to run on the fake repository or on the real one&lt;/li&gt;    &lt;li&gt;a WCF implementation of that repository which remotes calls from the web tier to the midtier&lt;/li&gt;    &lt;li&gt;several unit tests&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Have a look and let me know what you think.&amp;#160; Of course this is not the end-all-be-all of anything.&amp;#160; It’s just a sample designed to illustrate a few concepts, but maybe someone will find it useful.&lt;/p&gt;  &lt;p&gt;- Danny&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9617786" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/dsimmons/archive/tags/Entity+Framework/default.aspx">Entity Framework</category><category domain="http://blogs.msdn.com/dsimmons/archive/tags/Web+Services/default.aspx">Web Services</category></item><item><title>Cool things are coming in EF4!</title><link>http://blogs.msdn.com/dsimmons/archive/2009/05/12/cool-things-are-coming-in-ef4.aspx</link><pubDate>Tue, 12 May 2009 04:36:05 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9605427</guid><dc:creator>dsimmons@microsoft.com</dc:creator><slash:comments>1</slash:comments><comments>http://blogs.msdn.com/dsimmons/comments/9605427.aspx</comments><wfw:commentRss>http://blogs.msdn.com/dsimmons/commentrss.aspx?PostID=9605427</wfw:commentRss><description>&lt;p&gt;I’m off at TechEd this week talking to customers about the EF—especially about ways to be successful using the EF right now with 3.5sp1.&amp;#160; Meanwhile, though, we’re getting close to releasing the first beta of EF4 (yeah!).&amp;#160; As we gear up for that release, the team has begun a series of posts on the &lt;a href="http://blogs.msdn.com/adonet" target="_blank"&gt;ado.net team blog&lt;/a&gt; about all the great new features.&amp;#160; &lt;br /&gt;    &lt;br /&gt;Here are the posts released so far:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a title="Update on the Entity Framework in .NET 4 and Visual Studio 2010" href="http://blogs.msdn.com/adonet/archive/2009/05/11/update-on-the-entity-framework-in-net-4-and-visual-studio-2010.aspx"&gt;Update on the Entity Framework in .NET 4 and Visual Studio 2010&lt;/a&gt;: This has a quick overview of some of the most exciting new features—sort of a brochure if you will.      &lt;br /&gt;&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"&gt;Sneak Preview- Persistence Ignorance and POCO in Entity Framework 4.0&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;There are a lot more posts to come over the coming weeks.&amp;#160; So stay tuned to the blog, and let us know what you think.&lt;/p&gt;  &lt;p&gt;- Danny&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9605427" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/dsimmons/archive/tags/Entity+Framework/default.aspx">Entity Framework</category></item><item><title>Lots of EF Fun at TechEd Next Week</title><link>http://blogs.msdn.com/dsimmons/archive/2009/05/06/lots-of-ef-fun-at-teched-next-week.aspx</link><pubDate>Wed, 06 May 2009 07:45:22 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9590433</guid><dc:creator>dsimmons@microsoft.com</dc:creator><slash:comments>1</slash:comments><comments>http://blogs.msdn.com/dsimmons/comments/9590433.aspx</comments><wfw:commentRss>http://blogs.msdn.com/dsimmons/commentrss.aspx?PostID=9590433</wfw:commentRss><description>&lt;p&gt;I’m off to TechEd North America in LA next week where I’ll be presenting a 400-level session titled “Applied Entity Framework”.&amp;#160; The session will mostly be focused on helping folks be more successful using EF3.5sp1 but also with some info about features coming in EF4 and how to prepare for them.&amp;#160; If you are going to be at TechEd, you might want to check out DTL401.&amp;#160; &lt;/p&gt;  &lt;p&gt;There are quite a few other sessions that are either completely about the EF or contain EF content.&amp;#160; So I created the following I-Cal file which makes it real easy to view them all in Outlook or your favorite calendar system: &lt;a title="http://www.the-simmons.net/teched-2009-ef.ics" href="http://www.the-simmons.net/teched-2009-ef.ics"&gt;http://www.the-simmons.net/teched-2009-ef.ics&lt;/a&gt;&amp;#160; In addition to the break out sessions, there are some birds-of-a-feather sessions that sound like they will be very interesting.&amp;#160; A helpful resource for folks unable to make the conference in person or who want TechEd info before or after the conference is &lt;a href="http://msdn.microsoft.com/en-us/events/teched/cc527067.aspx" target="_blank"&gt;TechEd Online&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;While I’m there, I’ll also be spending plenty of time in the technical learning center and just generally hanging out trying to meet with folks to hear about what you are doing with the EF, to help solve any dilemmas you may be struggling with, and to help folks start getting excited about EF4.&amp;#160; While I’m on the topic of EF4 the first beta is coming pretty soon, but if you are at TechEd there will be a hands-on-lab where you can get an even earlier preview of the bits.&amp;#160; I know I’m biased, but I think EF4 is really cool.&amp;#160; I’m hoping it will really blow your socks off!&lt;/p&gt;  &lt;p&gt;One last thing…&amp;#160; &lt;a href="http://www.thedatafarm.com/Blog/2009/04/23/EF4EF4EF4.aspx" target="_blank"&gt;Julie Lerman recently posted&lt;/a&gt; about the fact that we have been referring to the next release of the EF as EF4 to help people keep straight the fact that this is the version of EF going out with .net 4, and that led to an email thread where she suggested that we get some t-shirts made which sounded like lots of fun to me.&amp;#160; I would have loved to get a whole bunch of these to give away at TechEd but given tight budgets that wasn’t in the cards (and make no mistake, I’d rather see Microsoft funds going into people and products than shirts).&amp;#160; So I did some hunting on the web and found a place that will make custom shirts in small lots and ordered a few to commemorate the fact that EF4 feels like a lot more than the average second release (in spite of the fact that we didn’t have a full release worth of time to devote).&amp;#160; The shirts look something like this:&lt;/p&gt;  &lt;p&gt;&lt;a title="v2 squared: EF4 T-shirt" href="http://www.zazzle.com/v2_squared_ef4_tshirt-235150309421493680"&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="v2_squared_ef4_tshirt-p235150309421493680aqiki_325[1]" border="0" alt="v2_squared_ef4_tshirt-p235150309421493680aqiki_325[1]" src="http://www.the-simmons.net/images/LotsofEFFunatTechEdNextWeek_131E3/v2_squared_ef4_tshirtp235150309421493680aqiki_3251.jpg" width="240" height="240" /&gt;&lt;/a&gt; &lt;a title="v2 squared: EF4 T-shirt" href="http://www.zazzle.com/v2_squared_ef4_tshirt-235150309421493680"&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="v2_squared_ef4_tshirt-p235150309421493680a3t7u_325[1]" border="0" alt="v2_squared_ef4_tshirt-p235150309421493680a3t7u_325[1]" src="http://www.the-simmons.net/images/LotsofEFFunatTechEdNextWeek_131E3/v2_squared_ef4_tshirtp235150309421493680a3t7u_3251.jpg" width="240" height="240" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;In the off chance that you are crazy like me and interested in such a shirt, you can get your own here: &lt;a title="http://www.zazzle.com/v2_squared_ef4_tshirt-235150309421493680" href="http://www.zazzle.com/v2_squared_ef4_tshirt-235150309421493680"&gt;http://www.zazzle.com/v2_squared_ef4_tshirt-235150309421493680&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;The way this site works, if you buy one of these, they give me a 10% kick-back, but I’m certainly not trying to make any money off of these shirts.&amp;#160; So any royalties that come my way from folks buying these will be donated to a local worthy cause: &lt;a href="http://ugm.org/"&gt;Seattle Union Gospel Mission&lt;/a&gt; which does a lot for the homeless and others dealing with hard times in the Seattle area.&lt;/p&gt;  &lt;p&gt;In any case, here’s hoping to see you next week!&lt;/p&gt;  &lt;p&gt;- Danny&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9590433" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/dsimmons/archive/tags/Entity+Framework/default.aspx">Entity Framework</category><category domain="http://blogs.msdn.com/dsimmons/archive/tags/Random_28002900_/default.aspx">Random()</category></item><item><title>Building N-Tier applications with the EF – The Basics</title><link>http://blogs.msdn.com/dsimmons/archive/2009/04/09/building-n-tier-applications-with-the-ef-the-basics.aspx</link><pubDate>Thu, 09 Apr 2009 08:08:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9539536</guid><dc:creator>dsimmons@microsoft.com</dc:creator><slash:comments>3</slash:comments><comments>http://blogs.msdn.com/dsimmons/comments/9539536.aspx</comments><wfw:commentRss>http://blogs.msdn.com/dsimmons/commentrss.aspx?PostID=9539536</wfw:commentRss><description>&lt;p&gt;Today I was looking at &lt;a href="http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/4b4b076e-bf7c-4cb8-ab72-b0b40104a1cc" target="_blank"&gt;a post in the forums&lt;/a&gt; where someone asked a very natural and common question about the EF that I end up answering pretty frequently.&amp;#160; So I decided to put my answer here on my blog to make it easier to refer back to the answer in the future.&amp;#160; The question was essentially this: &lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;I’m building a silverlight client (but it could just as easily be a rich client or an ajax app or any other client of a WCF service) with a WCF service on the mid-tier that uses the EF to persist changes to a database.&amp;#160; I can easily write a WCF service method to retrieve entities, and I can also create one which will add new entities to the database by just calling AddObject and then SaveChanges, but I can’t figure out how to do an update.&amp;#160; I was hoping there would just be an UpdateObject method or something like that.&amp;#160; What do I do?&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Unfortunately this is more difficult than we'd like it to be in EF3.5 (the first release).&amp;#160; It's a bit difficult because the problem space is more complicated under the covers than it seems to be on the surface, so you have to think carefully about a few things.&amp;#160; That said, the EF API could help more in these scenarios, so in EF4 we're working on a series of improvements which you can read about in posts on the EF Design blog such as this one: &lt;a href="http://blogs.msdn.com/efdesign/archive/2009/03/24/self-tracking-entities-in-the-entity-framework.aspx"&gt;http://blogs.msdn.com/efdesign/archive/2009/03/24/self-tracking-entities-in-the-entity-framework.aspx&lt;/a&gt;     &lt;br /&gt;In the meantime, there are three important things you need to think about:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Keeping track of concurrency tokens for the purpose of doing concurrency checks when you update (you don't want to blindly overwrite a change that some other client has made to the same part of the database between the time when you read the data and the time when you try to write back your changes).      &lt;br /&gt;&lt;/li&gt;    &lt;li&gt;Keeping track of which properties you have modified on an entity.&amp;#160; This is important if you want to make sure that the update to the database only includes the modified properties.&amp;#160; If you are OK with sending an update statement that includes even unmodified properties (which by the way can sometimes even be faster because it might allow the database to reuse a query plan rather than generating a new one for each combination of modified props), then it may be OK not to worry about this one.      &lt;br /&gt;&lt;/li&gt;    &lt;li&gt;If you have a graph of related entities then you need to worry about tracking what kinds of operations happened to what parts of the graph--one entity modified, another one is a newly added entity, another one deleted, etc. &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;All of this amounts to tracking this information on the client side, communicating it back to your mid-tier through your WCF service methods, and then replaying information to the ObjectContext so the changes can be persisted.&amp;#160; If you skip option #3 for now (one of the hardest parts with EF3.5 and something which can occasionally be skipped if you are willing to just have WCF service methods which operate on one entity or which treat all entities in the graph the same way--so you have separate methods for add, update and delete), then you already know how to do the add method.&amp;#160; The delete method is also pretty straight forward, you just need to call Attach on the entity you pass to the method to bring it into the context and then call DeleteObject on it and SaveChanges.&amp;#160; The interesting method, as you mention, is update...&lt;/p&gt;  &lt;p&gt;The simplest but not terribly efficient way to solve the update method is to make a copy of the entity on the client before you make any changes so that at the time you want to update things you have both a copy of the original version of the entity and the modified one.&amp;#160; Then your update service method can look something like this:&lt;/p&gt;  &lt;div id="codeSnippetWrapper"&gt;   &lt;pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &amp;#39;Courier New&amp;#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"&gt;&lt;span style="color: #0000ff"&gt;void&lt;/span&gt; Update(MyEntity original, MyEntity updated)&lt;br /&gt;{&lt;br /&gt;    &lt;span style="color: #0000ff"&gt;using&lt;/span&gt; (var context = &lt;span style="color: #0000ff"&gt;new&lt;/span&gt; MyEntities())&lt;br /&gt;    {&lt;br /&gt;        context.Attach(original);&lt;br /&gt;        context.ApplyPropertyChanges(updated);&lt;br /&gt;        context.SaveChanges();&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;

  &lt;br /&gt;&lt;/div&gt;

&lt;div id="codeSnippetWrapper"&gt;You can improve on this, though, if you are willing to make a few assumptions.&amp;#160; First, if you can guarantee that the client will not change the property used for concurrency checks, then you don’t need the original value of the concurrency property.&amp;#160; Secondly, if you are willing to always send all properties to the server on an update rather than just those properties which have changed, then you don’t need an original value for all the other properties to compare against to see if they are changed.&amp;#160; In this case you can get away with only sending a single, updated entity from the client back to the mid-tier, and you just have to use some trickier APIs to get the entity attached to the context in a form so that the EF will treat it as modified.&amp;#160; I wrote a &lt;a href="http://blogs.msdn.com/dsimmons/archive/2008/10/31/attachasmodified-a-small-step-toward-simplifying-ef-n-tier-patterns.aspx" target="_blank"&gt;previous blog post&lt;/a&gt; about how to do that.&amp;#160; With the extension method from that post, you can get rid of the original entity argument to the update method and just call the AttachAsModified method followed by SaveChanges().

  &lt;br /&gt;&lt;/div&gt;

&lt;div&gt;- Danny&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9539536" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/dsimmons/archive/tags/Entity+Framework/default.aspx">Entity Framework</category><category domain="http://blogs.msdn.com/dsimmons/archive/tags/Web+Services/default.aspx">Web Services</category></item><item><title>D3: Using T4 to Generate Entity and Context Classes</title><link>http://blogs.msdn.com/dsimmons/archive/2009/04/08/d3-using-t4-to-generate-entity-and-context-classes.aspx</link><pubDate>Wed, 08 Apr 2009 10:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9537585</guid><dc:creator>dsimmons@microsoft.com</dc:creator><slash:comments>1</slash:comments><comments>http://blogs.msdn.com/dsimmons/comments/9537585.aspx</comments><wfw:commentRss>http://blogs.msdn.com/dsimmons/commentrss.aspx?PostID=9537585</wfw:commentRss><description>&lt;P&gt;Sorry for the DPMud hiatus.&amp;nbsp; Here’s another installment for those interested in the process.&amp;nbsp; I’m still trying to get a public source repository up.&amp;nbsp; Until that’s functional I’m not going to do a lot of development because I want to share the process with you.&amp;nbsp; In the meantime I’m still laying groundwork where I can, and one aspect of that is using T4 to generate classes for the entities and for the data access layer.&lt;/P&gt;
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;EM&gt;Side Note: We’ve been trying hard to refer to EF versions using the corresponding .net version rather than “v1” and “v2” since talking in terms of .net versions makes it clear when and how the corresponding versions ship.&amp;nbsp; So don’t be surprised when I refer to EF4 or EF3.5.&lt;/EM&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;The idea behind using T4 for code generation is that I’d like to create the DPMud model using the EF Designer and then generate both the classes and the database from the model (&lt;A href="http://blogs.msdn.com/efdesign/archive/2008/09/10/model-first.aspx" mce_href="http://blogs.msdn.com/efdesign/archive/2008/09/10/model-first.aspx"&gt;database generation has been discussed previously on the EF Design blog&lt;/A&gt;).&amp;nbsp; There are two key architectural requirements for these classes that we generate:&lt;/P&gt;
&lt;OL&gt;
&lt;LI&gt;The entities should be completely &lt;STRONG&gt;persistence ignorant&lt;/STRONG&gt;.&amp;nbsp; That is, they should live in an assembly which doesn’t have any dependency on Entity Framework or ADO.Net DLLs.&amp;nbsp; One concrete reason for this is that I want to reuse the entity classes in Silverlight.&amp;nbsp; Happily, EF4 adds extensive support for POCO entity classes. &lt;BR&gt;&lt;/LI&gt;
&lt;LI&gt;The DAL should be designed in a way that supports easy introduction of a fake implementation.&amp;nbsp; That is, it should be a “seam” in the terminology of design for testability.&amp;nbsp; Another feature of EF4 which supports this is the introduction of a new interface, IObjectSet&amp;lt;T&amp;gt; which is implemented by the ObjectSet&amp;lt;T&amp;gt; class which provides both a starting point for queries and a place to add and remove entities of that type.&lt;/LI&gt;&lt;/OL&gt;
&lt;P&gt;So I created a couple T4 templates.&amp;nbsp; They share some infrastructure for helping to read EF metadata, escaping identifiers, generating multiple files, one per class, etc.&amp;nbsp; We’re working on getting that infrastructure into the core product, so I’ll concentrate on the unique parts of these templates.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;The entity template iterates over each entity type in the metadata and generates a partial class with each property marked virtual so that an automatic EF proxy can be generated if necessary.&amp;nbsp; For navigation properties, it generates properties that are simple CLR references or ICollection&amp;lt;T&amp;gt; instances with an implementation that does fixup.&amp;nbsp; The fixup implementation is generated so that it can be included in the entity DLL and not introduce any other requirements to the entity classes.&lt;/P&gt;
&lt;P&gt;The context template generates a class which inherits from ObjectContext and has properties that return ObjectSet&amp;lt;T&amp;gt; instances.&amp;nbsp; It also generates an interface for the seam with IObjectSet&amp;lt;T&amp;gt; properties and a fake context implementation which has fake object set instances which have a very simple wrapper around hashset&amp;lt;T&amp;gt;.&lt;/P&gt;
&lt;P&gt;This way I can put the entities into one DLL and the context, interface and fake context into a separate DLL for the DAL.&lt;/P&gt;
&lt;P&gt;- Danny&lt;/P&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9537585" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/dsimmons/archive/tags/Entity+Framework/default.aspx">Entity Framework</category><category domain="http://blogs.msdn.com/dsimmons/archive/tags/D3/default.aspx">D3</category></item></channel></rss>