Saturday, September 8, 2012

Entity Framework Code First Web.config Initialization

Even though as a blogger you often blog code, blogs aren't working code, obviously. A blog post about a particular technology will slowly fade in relevance as time passes and the world moves on. But at the same time if a better way of doing something that you recently wrote about comes along, you'd want to update the post in question, so that's what I'm doing here about EF Code First Migrations, now that we're up to EF 5.0.

In Entity Framework Migrations strategies: the Semi-Automatic I talked about the DbMigrator class to run your migration scripts, invoked from the global.asax on Application_Start() for instance, but that was then: this is now. Or as they say in Perth "Yeah ... nah!". The way you specify the initializer for your DbContext has changed a lot in recent times, exhibiting all the stability of a game of jenga. But since the Jan 12 EF 4.3 Configuration File Settings post from the ADO.Net team, we can all consider ourselves schooled in the state-of-the-art in EF Code First initialization options, and should therefore move the whole show to the nearest config file.

Flickr photo
FlickrTransformers-Movie-Screen-Shots-04, by jalopnik. Web.config Transformer Man

Since EF 4.3 there has been an entityFramework section in the Web.config and as the EF team point out in that blog post you can use this to set a migration strategy. Much better than doing it through the code. Why? Because obviously you may not have the same strategy in your local dev, testing, and production environments. "...if you are using Code First Migrations, you can configure the database to be migrated automatically using the MigrateDatabaseToLatestVersion initializer." Did you get that? There's a new addition to the original 3 initializers included with EF:
  1. CreateDatabaseIfNotExists (default)
  2. DropCreateDatabaseWhenModelChanges
  3. DropCreateDatabaseAlways
  4. MigrateDatabaseToLatestVersion <- now that's what I'm talking about!
You can completely disable initialization too, by simply changing the disableDatabaseInitialization value to "true". You may be nervous about the unintended side-effects of EF Code First on your production database, so it's nice to have an off switch like this. Let's be perfectly honest here - running any sort of initialization option against a live database is not for the faint-hearted.

To get cracking with this new initializer, just associate it with your context in your app's Web.config:
<configuration>
  ...
  <entityFramework>
    <contexts>
      <context type="MyAssembly.MyContext, MyAssembly" disableDatabaseInitialization="false" >
        <databaseInitializer type="System.Data.Entity.MigrateDatabaseToLatestVersion`2[[MyContext, MyAssembly], [MyConfiguration, MyAssembly]], EntityFramework" />
        </context>
      </contexts>
   </entityFramework>
<configuration>
That databaseInitializer type attribute value is just confusing: at least I found myself confused the first time I had to whip one of these up in the web.config, so it might help to think of it as being the same as:
Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, MyConfig>());
The MigrateDatabaseToLatestVersion generic initializer takes two type parameters - "When we create an instance of this initializer we need to specify the context type and the migrations configuration - the migrations configuration is the class that got added to our Migrations folder when we enabled Migrations.", from the Code First Migrations article in the MSDN Data Developer Center - so that's why there's the `2 in the config.

Remember that this new web.config option still requires that you explicitly run through the 'add-migration...' and 'update-database' steps I outlined in my last EF post. The purpose of this post is just to concentrate on moving the old code-based DbMigrator functionality into the web.config, since that sort of thing - your choice of initialization strategy - is perfectly suited to an environmentally configurable setting, much like a service endpoint or email address.

Flickr photo
FlickrTransformers DOTM Deluxe Bumblebee 05, by Gabo440. Transform that Web.config!

Transformers

Right, well, if you are going to use web.config Entity Framework initialization, then you definitely want to use Web.config transformations. They just go together so well. Let's say you have a particular initialization strategy for your local dev environment - DropCreateDatabaseWhenModelChanges, so you can just blow away your database every time it changes, whereupon it gets reseeded with some minimal data. That's what I do. And obviously you want the same thing in production. Only joking. That was a joke. You want MigrateDatabaseToLatestVersion, or maybe you want to switch initialization off completely. So how do you manage the change in the web.config. Manually?

Without going into too much detail, if you're using Visual Studio to deploy your solution then don't do it manually - it's a natural fit to use Web.config transforms. But even if you aren't, I still say it's beneficial to let Visual Studio perform a transform since you can easily create a transform file and preview that transform, and make your actual testing, staging, or production Web.config from that.
"...you can see a preview of the changes in Visual Studio. In Solution Explorer, right-click the transform file (for example, Web.Release.config) and select Preview Transform. Visual Studio shows the original Web.config file and the transformed Web.config file side by side."
So, the following section is part of a transform file I use at work which switches off initialization, both by setting the disableDatabaseInitialization attribute to true on the context, and then for good measure removing the databaseInitializer node itself. The attributes starting with "xdt" belong to the XML-Document-Transform namespace: they do the transforming magic here.
<entityFramework>
  <contexts>
    <context type="MyAssembly.MyContext, MyAssembly" disableDatabaseInitialization="true" xdt:Transform="SetAttributes">
      <databaseInitializer xdt:Transform="Remove"/>
    </context>
  </contexts>
</entityFramework>
I said I wouldn't go into that much detail about config transformations because you could write a whole blog post on the ins and outs of the different types of transformations that are possible. You have to admit, anything that varies by environment ultimately should end up in one or other of your config files, and your choice of EF initialization strategy will surely vary by environment. It's such a natural fit - web.config EF initializers and web.config transformations. They're like Fred Astaire and Ginger Rogers. I really should have used a picture of ol' Fred and Ginge dancing in "Swing Time" to illustrate this point, but I just got carried away with the whole Transformers thing.

34 comments:

  1. Dude, this is exactly what I was looking for. I needed to initialise my Migrations code in the web.config and now I know how to do it. Thanks a million.

    ReplyDelete
  2. Sachin

    This is even better than Entity Framework:
    https://www.kellermansoftware.com/p-47-net-data-access-layer.aspx

    ReplyDelete
  3. Nice post. I was checking constantly this blog and I’m impressed! Extremely useful info specially the last part I care for such information a lot. I was seeking this certain info for a long time. Thank you and good luck. freelance web designer peter

    ReplyDelete
  4. I found your this post while searching for some related information on blog search...Its a good post..keep posting and update the information. Web Designing

    ReplyDelete
  5. Im no expert, but I believe you just made an excellent point. You certainly fully understand what youre speaking about, and I can truly get behind that. Web Designing

    ReplyDelete
  6. That is really nice to hear. thank you for the update and good luck. web design company lakeland

    ReplyDelete
  7. It was a very good post indeed. I thoroughly enjoyed reading it in my lunch time. Will surely come and visit this blog more often. Thanks for sharing. website design inspiration

    ReplyDelete
  8. This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here! keep up the good work theymakedesign

    ReplyDelete
  9. Interesting topic for a blog. I have been searching the Internet for fun and came upon your website. Fabulous post. Thanks a ton for sharing your knowledge! It is great to see that some people still put in an effort into managing their websites. I'll be sure to check back again real soon. design

    ReplyDelete
  10. It is imperative that we read blog post very carefully. I am already done it and find that this post is really amazing. Professionele webshop laten bouwen

    ReplyDelete
  11. Excellent and very exciting site. Love to watch. Keep Rocking. here

    ReplyDelete
  12. Great Information sharing .. I am very happy to read this article .. thanks for giving us go through info.Fantastic nice. I appreciate this post. best brand agencies

    ReplyDelete
  13. Quality Magento Web design and development intends to bring the finestin your ecommerce website so that you're able to expand your on-line store for an unprecedented speed. web design singapore

    ReplyDelete
  14. Thanks for the useful information, love reading stuff from your blog! web development company

    ReplyDelete
  15. Cheap Replica Handbags You guide me by sharing this toolbox i face problem whenever i exploit this promotion reading your blog i am able to easily use. ui design agency san francisco

    ReplyDelete
  16. Hello! Wonderful post! Please when I could see a follow up! iphone device template

    ReplyDelete
  17. I enjoy you because of all of your labor on this blog. My niece loves going through investigations and it is easy to understand why. We know all relating to the dynamic form you offer sensible things through the blog and in addition inspire participation from others on this concept plus our favorite child is actually becoming educated so much. Take pleasure in the rest of the new year. You’re the one performing a useful job. ipad png

    ReplyDelete
  18. Single codebase is sent over all stages (snappier turn of events) and there is no compelling reason to experience any endorsement procedure. 먹튀

    ReplyDelete
  19. Nice post. I learn something more challenging on distinct blogs everyday. It will always be stimulating to read content off their writers and practice a little something from their store. I’d choose to use some with all the content in my small weblog whether you do not mind. Natually I’ll provide a link on your own internet weblog. Many thanks sharing. web designer san francisco

    ReplyDelete
  20. Web development agency seems like a magic that will make your website stand out from your competitors. We are known for creating powerful and professional websites that will stand out from the rest. web development services in usa

    ReplyDelete
  21. hello!,I really like your writing so a lot! percentage we keep up a correspondence extra about your article on AOL? I require an expert on this area to unravel my problem. Maybe that's you! Taking a look ahead to look you. web design agency san francisco

    ReplyDelete
  22. Things i have seen in terms of computer memory is the fact there are technical specs such as SDRAM, DDR and many others, that must match the features of the motherboard. If the personal computer’s motherboard is fairly current while there are no operating-system issues, changing the memory literally takes under sixty minutes. It’s one of several easiest personal computer upgrade techniques one can picture. Thanks for giving your ideas. website design firms san francisco

    ReplyDelete
  23. Watch the strategies presented continue reading to discover and just listen how to carry out this amazing like you organize your company at the moment. educational web design company san francisco

    ReplyDelete
  24. Hi there! This is my first visit to your blog! We are a team of volunteers and starting a new project in a community in the same niche. Your blog provided us beneficial information to work on. You have done a extraordinary job! web design san francisco

    ReplyDelete
  25. I am often to blogging and that i really appreciate your content regularly. The article has truly peaks my interest. I’m going to bookmark your website and maintain checking for brand spanking new data. los angeles web agency

    ReplyDelete
  26. I’d need to consult you here. Which isn’t something I do! I quite like reading a post that could make people think. Also, thanks for allowing me to comment! los angeles web design

    ReplyDelete
  27. To make a brand, an advertiser must have scale and nearness. smm panel

    ReplyDelete
  28. Great post, you have pointed out some fantastic details , I too conceive this s a very fantastic website. website tips

    ReplyDelete
  29. How much of an significant content, keep on penning significant other website tips

    ReplyDelete
  30. Gnarly article mate, keep the good work, just shared this with ma friendz web design

    ReplyDelete