It seems like for forever I have been dealing with the problem of deploying software and keeping the database updates synchronized at the same time. I’m sure you’ve been there too. If you are developing software, you likely need database schema changes from time to time (or much more often). If you are running a local copy of the database for development (I like working like that), you can easily make the change on your local SQL Server instance (or some other database product). But then you need all of your teammates to update their database instances with the changes. Of course, they may have changes to the schema as well. All that, plus sooner or later you will need to deploy these changes to the test, staging or production database.

Where I have worked we used a variety of techniques to accomplish this goal but it has never been easy. Finally, Microsoft gives us Entity Framework Migrations! This makes this situation very easy to deal with!

Here are some steps to get started with Migrations. I was surprised with how easy this is to use. To be fair, I haven’t pushed this technology much past the basics but it is working quite nicely on my project so far. Also I’m using EF Code First which is really cool but in this post, I won’t be explaining all of the parts of that. I’ll mention the basic steps but if you want to learn more about the many features of EF Code First, you’ll need to look elsewhere.

Beware, I am running Visual Studio 11 Beta, .Net 4.5 Beta, Entity Framework 5 Beta. You should be able to accomplish this stuff with earlier versions too.

Step By Step Guide to Getting Started with Entity Framework Code First Migrations (in C#)

  1. Create a new application. I’m working with a simple C# Console App.
  2. Install Entity Framework. You can do this via the Nuget Package Manager UI or the Package Manager Console. Again, I am using beta so I’ll need to use the console with this command: PM> install-package EntityFramework –includePreRelease
  3. I did get an error when I did that. I don’t recall getting that error in the past but to resolve the error, I used the Add Reference Dialog and added a reference to System.ComponentModel.DataAnnotations. Then I re-tried the console command and it worked just fine.
  4. After installing EntityFramework, my app.config looks like this:
    <?xml version="1.0" encoding="utf-8"?>
        <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection,
    EntityFramework, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> </configSections> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /> </entityFramework> </configuration>

    Thanks NuGet!

  5. Next we’ll need to create an entity that needs to be in our database. In my application, I need a simple object to represent movies.
        public class Movie
            public int Id { get; set; }
            public string Title { get; set; }
            public string Year { get; set; }
            public string Studio { get; set; }

    You will note that I did NOT annotate this class with any attributes at all.

  6. Next we’ll need to create our DbContext. It too is pretty simple.
        public class MovieContext : DbContext
            public DbSet<Movie> Movies { get; set; }
  7. Ok for this simple sample, my initial data schema is done. Since this is Code First however, my database doesn’t actually exist yet. Let’s have Entity Framework create it for us. To do so, we need to run our application. Before running it, just add this code to the Main method of your console app. If your application doesn’t “use” the DbContext, it won’t be generated.
        MovieContext context = new MovieContext();
        foreach(var movie in context.Movies)

    Now just run the app. If you’ve got SqlServer Express installed, you will now have a new database in there that looks like this:image

    Yes, the Id was automatically turned into a primary key. Sweet, huh? Code First Rocks!

  8. Now we have a database and a schema but we haven’t used migrations yet! Let’s get started with that. Back in the NuGet Package Manager Console, type this: PM> enable-Migrations 
  9. When you enable migrations, it will create a Migrations folder in your project with two files.
    • 201204190017084_InitialCreate.cs (your name will vary). This file contains the code to create your database schema from scratch. In this case, there is only one table. This will be important because after we do our next migration, we may need to roll back to our initial design.
    • Configuration.cs which is used for… you guessed it, configuration of Migrations. One important setting is AutomaticMigrationsEnabled. With that set to true, EF will always migrate your database when you run your application and it detects that your context is out of sync with your db.
    • Check out these files and you will see how simple this stuff is. Each migration contains an Up() method and a Down() method. This enables you to migrate your database up and down to any version!
          public partial class InitialCreate : DbMigration
              public override void Up()
                      c => new
                              Id = c.Int(nullable: false, identity: true),
                              Title = c.String(),
                              Year = c.String(),
                              Studio = c.String(),
                      .PrimaryKey(t => t.Id);
              public override void Down()
  10. Now we need to make a change: Add something to the Movie class, something like this: public string Genre { get; set; }
  11. Now if we run our application (remember that we do NOT have Automatic Migrations Enabled). We’ll get an error:image

    In this case, that is perfect and just what we expected.

  12. Back to the Package Manager Console: PM> add-migration Genre That command will create a new Migration file for us with just what we need:
        public partial class Genre : DbMigration
            public override void Up()
                AddColumn("Movies", "Genre", c => c.String());
            public override void Down()
                DropColumn("Movies", "Genre");
  13. Next, this command in Package Manager Console: PM> update-database You’ll get some messages confirming the action. When I check my database I’ll see that the new column was added just as I needed. I can now run my application successfully again. Too bad my application doesn’t do anything.

Eventually, you will have multiple migrations in your project. If you need to revert back to an old version of code, you can also revert back to an old version of the schema by specifying which a target. In this example, I want to target the migration named “InitialCreate”: update-database –TargetMigration InitialCreate

To create scripts instead of actually updating your database, you can use a command similar to this: update-database -Script -TargetMigration Genre These scripts can be saved and used as part of your deployment process.

Those are the basics of Entity Framework Migrations. I think you will find it is pretty easy to use. For more information, I suggest you follow the ADO.Net Team Blog.

Download my sample solution:

I’m a few weeks into a side project that I blogged about in a previous post. I’m having a lot of fun (I’m such a geek) using a bunch of new stuff. Since Visual Studio 11 is at the center of all the work on the project, I thought I’d share my first impressions on it. Of course, I’m using a Beta version of it. Really this post is about my second thoughts since they are much more meaningful. Spoiler alert: First impressions aren’t always the most important.

My first thoughts

My first thoughts were pretty typical and can be summarized with one bullet:

  • Colorless

That is pretty much what most people think when they see it for the first time. People tend to ignore all of the improvements and new features and focus on the lack of color. At first I found this lack of color to be somewhat distracting which is odd because it is meant to have the opposite effect. I’ll be honest, I wasn’t thrilled with the new look but I was quick to point out to some of my peers that we should give it some time and get used to it.

My Second Thoughts

Guess what? I got used to it… quickly. After using Visual Studio 11 for a couple of hours, I quickly got used to the lack of color. It isn’t really that big a deal and I think the VS team was on the right track by moving Visual Studio overall to the background and making the code editor the focal point. Having said that, I still think some color would be helpful. My last point on the overall lack of color is that it isn’t 100% consistent. Some windows within VS11 still have color. And some plugins use color too. That makes things a bit odd. I’m including a screenshot below. That’s all for the color.


Some features to note (this is by no means a comprehensive list, just some highlights):

So far, I think VS11 is an awesome development environment. I’ve been doing MVC development within VS11 and the HTML, CSS, and JavaScript support is really nice. VS11 is now providing a lot of help for developers working in these areas. I’ll also point out that I am using ReSharper (v7 EAP for VS11). I love ReSharper! Between VS11 and ReSharper, the web development experience is awesome. I’ll be honest, I don’t always know which tool is providing the various features!

When developing web apps, we typically want to run/debug/test them in a variety of browsers. It seems like Microsoft has figured out the IE is not the only browser in town. So now we can use the Debug Target toolbar button. Just click the typical “play” button or hit F5 to debug in which ever browser is selected: image Or you can use the drop down to chose a different target or change the default:


I like the fact that the great features of the Solution Navigator (previously part of the Productivity Power Tools) were combined into the Solution Explorer. Of course, the Add Reference dialog is a huge improvement from the past, that was also a feature from the Power Tools.

I’m also a huge fan in the reduction of items in the toolbars. I think the VS team really nailed that part of the design as well. They took out all but the most commonly used buttons from the toolbar – but only in the default configuration. If there is a button or toolbar you like, just add it back in. That part is easy! More importantly, we should all get used to the Quick Launch feature. With that, we can just type the name of any command we want. No more hunting around in the menus for seldom used actions!

Another great feature is the Preview Tab. I’m surprised more people aren’t talking about this one. This is pretty cool but I don’t think you can get the full value of it until you experience it yourself. Think about all those times you are debugging and you end up stepping into file after file after file. All those files get opened up in the tab well. Eventually you get to the file you want in the debug process. But when you are done you have a ton of open files. Not everyone is like me, but I hate open files. I want my tab well to be as empty as possible. Preview Tab to the rescue! With VS11, all of those files that you step through don’t open up as normal files, they open in the Preview Tab. But Preview Tab only has one file at a time. So each new file you step into replaces the old one and your environment stays clutter free. And Preview Tab is pretty smart too. If you make a change to the file it moves it into the normal tab well. You can also click a button in the tab to “promote” the file to be a normally opened file. In this image you can see the Preview Tab on the right, circled in blue.


While it isn’t really new, I want to mention that the extensibility features of VS11 (and 2010 too) are really powerful and work so well and somewhat seamlessly. The Extension Manager is really cool and with it I’m always adding tools to Visual Studio. There are loads of great things to install. With VS2010 I hadn’t gotten to experience Nuget but with the work I’m doing now in VS11 I am all over it. Nuget (or is it NuGet, or nuget?) is providing all kinds of good stuff for my solution. Between VS11, the extensions and nuget packages, I really feel empowered to create great solutions.

There are lots of other great features, these are just the ones that came to mind as I was writing. Download the Beta and check it out for yourself!

A lot of new stuff has been coming out from Microsoft lately. Couple that with all the cool open source projects available for use and a developer can quickly get left behind from all the new technology. I try to stay pretty current but there is some new stuff that I’ve been wanting to use. I also wanted to brush up on some old skills and even use some of the technologies I am experienced with in new ways. I decided it was time to start a little project for myself. I’m often asked by developers about how they can gain experience with new technology (or even old tech that is new to them). My advice is that they should just write an application that uses the technology. As a hiring manager, I’ll give serious consideration to that kind of experience, provided it isn’t “hello world”. When I write an application like this, I treat it like a real world production project. And if you are creating a web application you can have it hosted and then it IS a real product. That should count as experience to a smart hiring manager. So when you write these applications, try to follow all of the best practices, use good standards, etc.

In my case, I am writing an application that I hope will actually get some use. I’m hoping to get some great blogging material out of this as well. I already have, but now I need to find time to write about it. Anyway, figure out what you want to build and then create a list of the things you want to learn. As you write the application, you can just keep adding other technologies, frameworks or patterns in along the way.

Here is my list of things I’m using or will be using in my new pet project. Obviously the beta stuff is brand new. And I’ve already got experience with MVC 2 (pre-Razor), jQuery, HTML, CSS, etc. However, this stuff gets better and better all the time and I like to stay on top of it. Working a few hours here and there for the past 2 weeks, I’ve already included all of the items in blue in my project.

  • Visual Studio 11 (beta)
  • Entity Framework 5 (beta)
  • Entity Framework Code First
  • Entity Framework Migrations
  • ASP.Net MVC 4
  • Razor
  • HTML 5
  • jQuery
  • jQuery UI
  • Git
  • Open Authentication
  • CSS3 & Media Queries
  • HTML/CSS Grid Systems
  • NuGet
  • SEO Toolkit (Microsoft)
  • C# 4.5 (including Async)
  • SignalR
  • Azure
  • ASP.Net Web API
  • BootStrap (from Twitter)
  • Facebook Integration
  • Of course, Dependency Injection, Unit Testing, and all of the other stuff I put into any app I am deploying.

I’m writing this as a web application and creating a mobile version at the same time. In addition, I plan to extend this to additional platforms. So my list continues:

  • Mobile Web
  • WP7
  • Metro (Windows 8)

Philly.Net recently had a very successful event called CSharpenUp. We spent the day talking about some advanced topics for C# developers. We had 4 speakers and 80+ attendees. The feedback was very positive, everyone learned a lot and had fun too. If we can set it up, we’ll do the same event in the fall for those that missed it.

I’m still gathering code samples from the other presenters. But for now, here is mine:

Code samples and slides for my LINQ session: Intro to LINQ

Code samples and slides for my Unit Testing session: Unit Testing Made Easy

Also, FYI we did try to record the sessions using Camtasia. Unfortunately, the mic we used wasn’t that great. I’m trying to salvage mine but I may just re-record them.

When I write code, one of my big concerns is how will I test it. I’ve learned that when I see a static method, it is going to make things more complicated than I would like. However, resolving that isn’t usually too difficult. Converting a string value into an Enum is a perfect example. Of course, parsing the string may succeed or fail and I need to know how my code will behave in either case, hence the reason for the unit tests.

In order to make unit testing a bit easier, I wrote a simple class to help out. Basically, this class “wraps” Enum.TryParse() and of course, implements and interface. I’m also using some simple generics to make the casting a little prettier. Since I used an interface, I can now using MOQ, RhinoMocks, or any other framework to mock my dependency and control how it behaves.

You may note that I didn’t call the methods Parse. Instead, I used the name Adapt. That is just a naming convention of my current project so it made sense to be consistent. Feel free to rename this as you wish :)

Here is the interface:

public interface IStringToEnumAdapter
     T Adapt<T>(string value) where T: struct;
     bool TryAdapt<T>(string value, out T? result) where T : struct;

You’ll probably notice that my generic constraint is struct. That is because you can’t use Enum as a generic constraint. So struct is the best I’ve got to work with. And considering we are doing parsing here, if you pass any other stuct in, it is going to fail on the parse anyway. So I think it is pretty safe.

Here is the implementation:

public class StringToEnumAdapter : IStringToEnumAdapter
    public T Adapt<T>(string value) where T : struct
        T result;
        bool success = Enum.TryParse(value, true, out result);
        if (success)
            return result;
        throw new InvalidEnumArgumentException(string.Format("{0} could not be converted to {1}", value, typeof(T).Name));
    public bool TryAdapt<T>(string value, out T? result) where T : struct
        T parsedValue;
        bool success = Enum.TryParse(value, true, out parsedValue);
        result = success ? parsedValue : (T?)null;
        return success;

Guess what? It isn’t all that complicated right? If you are getting into testing, you’ll soon find out that simple steps like this make life a lot easier.

Click here to download the class and unit tests for it too.