Archives for February 2014

Migrating a Project from Database First to Code First

Overview

So you just pushed you application to production and used Microsoft’s new shiny ORM. It’s 2008 and you’re on the bleeding edge of .NET technology by implementing Entity Framework. Your EDMX paired with your database project keeps your project nice and organized in source control. Great Job. But fast forward to today, and Entity Framework Code First is all the rage. What do you do with that aging database first design along with that EDMX in all it’s glory ? Nuke it. You don’t need it anymore.

I sure hope you didn’t just blindly nuke it and check in. We still do need that EDMX for a bit, but not for long. We’re going to walk through the process of converting your old busted to the new hotness of Entity Framework Code first.

Migrations are you friend, but not like the kind you leave alone home with your significant other. Be sure to use them, but I highly recommend turning off automatic migrations. Anything that has that much blind control of your app should be something that you should VERY carefully consider before turning on.

Note: This process assumes you are using the Database First approach, and not the Model First Approach. If you use the model-first approach, you will have some leg work to do in order to determine what your EDMX might be doing that cannot be reverse engineered from the database.

Disclaimer: This is a fairly significant change you will be making to your project, so make sure that you plan for the regression testing of everything.

Now, let’s get on with it:

Step 1 : Generate your Context, Entities, and Mapping Files

Microsoft has released a visual studio plugin () that will generate POCOs and a context based on an EDMX. This will save you a whole lot of time. Head on over here, and install this plugin.

Once installed, move over to you project, and right click your Project File. There should now be a context menu item, Entity Framework, Select That, and then Reverse Engineer Code First.

generate_views

Select the database you would like to use to base the reverse engineer process to be based on.

generate_diag1

Once you click OK, a folder will be created in your project called Models that contains your new Context, Entities, and Fluent mapping configurations.

generated_files

Step 2: Remove old context, and update the project to use the new context.

Now that you have created all of your new entities and context, the old one can be removed. Delete the EDMX and all associated files (context.tt, etc).

Step 3: Enable Migrations

As I mentioned before, we are NOT enabling automatic migrations. We are only enabling migrations. This means that we will manually create migrations by using the add-migration syntax in the Package Manager Console.

In the Package Manager Console, Make sure that you set the Default Project to the project that contains your context. Then enter the command Enable-Migrations

enable_migrations

You will notice that a Migrations folder has been created with a Configuration.cs file.  In the Configuration.cs file, make sure Automatic Migrations is set to false.

Step 4: Create and Set Database Initializer

Create a new class called MyDbInitialzier

using System.Data.Entity;
using MyProject.Data.DataAccess.Migrations;

namespace MyProject.Data.DataAccess.EntityFramework
{
    internal sealed class MyDbInitializer : MigrateDatabaseToLatestVersion<MyDbContext, Configuration>
    {
    }
}

You will notice that I the initializer calss inherits from the MigrateDatabaseToLatestVersion class.  It is likely that this is the Initializer behavior that you will want to use if you have an existing database already in production.  If you have special circumstances, be sure to review all of the default initializers and/or look into building a custom initializer.

Step 5: Implement the new Context

You will want to crack open you web config and replace the old connection string (The one with all of the metadata stuff, with a new connection string.  The new connection string should look like any old ADO.NET connection string.

You will now want to replace the references to the old context with the new one. (Shortcut: you could just rename the new one to match the old one’s name).

Note: You may encounter a bit of a gotcha here.  Since the new context is of type DbContext and the old one was of type ObjectContext, you may find that some the compiler is complaining about some things.  The DbContext is kind of a wrapper for the object context that is meant to be lighter weight, there are things you may be using that are not supported by the db context.  You will want to research any of these issues that come up to see if the DbContext can support them. If all else fails, the DbContext can be cast to the ObjectContext if you absolutely need it.  (This will result in a performance hit, so use wisely).  The syntax for getting the ObjectContext from a DbContext is:

public class MyContext: DbContext
{
    public ObjectContext ObjectContext()
    {
        return (this as IObjectContextAdapter).ObjectContext;
    }
}
Step 6: Create Your Initial Migration

If we tried to run the project right now, the application would encounter an error letting you know that there are pending changes that need to be included in a migration before the application can proceed.  We are going to create our initial migration. In the Package Manager Console, enter the command Add-Migration initial

add_migration_initial

In your Migrations folder, a file should have been created: YYYYYYDDHHMMSSS_initial.cs. This should be a total representation of your entire existing database.

EF keeps track of changes to the data model updating a table in your database called __MigrationHistory (in SystemTables) Since your database is existing already, you do not have this table in your database, so when this migration goes to run, it will attempt to re-create all of the objects in your database. This is bad, and we dont want that.  We can use this trick to tell EF to not re-create all of the objects when it attempts to run this migration.  In your initial migration class, comment out all of the code in the Up method.  That’s it, that’s the whole trick.

public partial class initial : DbMigration
 {
    public override void Up()
    {
        // Commented Code Here
    }
}
Step 7: Update the Database

Now is the time to update your database.  In the package manager console, enter the command, Update-Database.

udpate-database

This will create the __MigrationHistory table and will record that it ran this initial migration, so moving forward it will view your database as ‘up to date’ with your data model. (If you want to create the database from scratch using code first from now on, you will need to uncomment this migration.  It can safely be uncommented after it updates the existing database).

That’s it.  You should now be able to run your project. Now you need to regression test everything really well.

Conclusion

By following these steps you should now be fully running on Code First with Migrations.  Happy Coding!

OpsHub and Polaris Solutions Announce Partnership to Drive Collaboration and Efficiency of Teams in the Software Development Lifecycle

OpsHub and Polaris Solutions announce partnership offering software development organizations a comprehensive Team Foundation Server (TFS) based solution for quick and easy adoption of Team Foundation Server (TFS), driving collaboration and efficiency of cross-functional teams in the software development lifecycle.

Palo Alto, CA, Chicago, IL and St. Louis, MO— OpsHub and Polaris Solutions Announce Partnership to Drive Efficiency of Teams in the Software Development Lifecycle—OpsHub and Polaris Solutions are pleased to announce a partnership enabling easy adoption of Team Foundation Server (TFS) to drive collaboration and efficiency of teams in the software development lifecycle. With this partnership, OpsHub and Polaris Solutions can offer the industry leading Application Lifecycle Management (ALM) integration and migration platform with Team Foundation Server (TFS) expertise and best-in-class ALM implementation and consulting services.

OpsHub and Polaris Solutions are both Microsoft Visual Studio 2013 Launch Partners and have strong ties in the Microsoft partner and customer ecosystem.

OpsHub Integration Manager’s broad ALM support addresses the challenges faced by larger corporations looking at Team Foundation Server (TFS) adoption within their heterogeneous ALM environment. Polaris Solutions has best-in-class ALM implementation and consulting services with expertise in Team Foundation Server (TFS) adoption for the most challenging environments.

“The OpsHub and Polaris Solutions partnership, provides great value to our customers, by helping them quickly adopt Team Foundation Server (TFS) within their heterogeneous ALM environments. Our combination of powerful integration tools and deep implementation experience will help drive efficiencies and collaboration between cross-functional teams working on multiple projects in the software development lifecycle.” said Chris Kadel, Principal at Polaris Solutions.

“Our customers will greatly benefit from the deep TFS expertise and best-in-class ALM implementation and consulting services of Polaris Solutions,” said Sandeep Jain, President and CEO of OpsHub, “and will be able to quickly adopt to Team Foundation Server (TFS) using OpsHub’s integration and migration platform, reaping the rewards of Visual Studio that much faster.”

OpsHub delivers their on-premise and cloud-based solutions to enterprises around the globe.

About Polaris Solutions

Polaris Solutions is an Application Lifecycle Management (ALM) consulting firm with offices in Chicago, St. Louis, and Denver. Polaris Solutions specializes in helping teams deliver high value software through technical leadership, process improvement, and software development expertise. Polaris Solutions provides industry proven expertise in software delivery and deep technical knowledge to its clients. It offers fresh insights and new directions to help companies take their next step forward with today’s powerful technologies.

http://www.polarissolutions.com.

For more information: info@polarissolutions.com

About OpsHub

OpsHub is the leading provider of Application Lifecycle Management (ALM) integration and migration solutions for application development organizations. OpsHub creates a unified ALM ecosystem by seamlessly combining individual ALM systems, enabling agility at scale.

The OpsHub solution provides the most comprehensive out-of-the-box integration and migration solution within the ALM ecosystem. Its span across ALM functionality, includes requirements management, source control, bug tracking, test management, release management, and customer support.

The OpsHub solution enables quick migration and seamless integration between leading ALM systems including those from HP, Microsoft, IBM, Accept, Atlassian, Rally, Serena, and more. OpsHub delivers their on-premise and cloud-based solutions to enterprises around the globe. For more information, visit http://www.opshub.com.

For more information, press only:

Jyoti Jain

marketing@opshub.com

 

For more information on OpsHub support for Microsoft Visual Studio 2013, visit:

http://www.opshub.com/tfsinfo

Polaris is a Platinum Sponsorship for Chicago Code Camp 2014

Polaris has just signed on as a Platinum Sponsor for this year’s Chicago Code Camp at the College of Lake County campus on April 26th, 2014.

Chicago Code Camp is a free, community-driven developer conference. Over 200 attendees and 17 sponsors filled the campus of College of Lake County last year and this year is shaping up to be even better.

This amazing event is completely free, so head on over and register now!

Polaris Solutions is a Gold Sponsor for Agile Gravy STL 2014

We’re proud to announce that we just signed on as a Gold sponsor for the first annual Agile Gravy St. Louis conference – a rich & savory 1-day Agile conference experience that’s worth soaking up every last drop. Early bird registration is $99.

The event will be held on Thursday, April 10th at the St. Louis Marriott West. Drop by our booth and say HI!