The Self-Taught Programmer

Recipes from real-world experience with asp.net.

How to Add a New Table to an Existing Database via EF Code-First Migrations

leave a comment »

The Situation:

You have been using Entity Framework code-first migrations with an existing database. Making changes to an existing table, such as adding a new field, go smoothly, and the database is updated correctly when you run an “Update-database” command. However, when you create an entirely new entity in your model and run “Update-database”, the new table doesn’t get added to your database. You get the “No pending code-based migrations” message.

A Solution:

I spent some time today researching this on StackOverflow and other forums and came up with no solution. It wasn’t until I started to think through the details of the process that EF migrations goes through that I found the answer.

EF migrations use a Configuration.cs file, which specifies an EF dbContext to use in communicating with the database. The context file lists all the entities that it manages. Therefore, you must add the new entity to the context file!

Once you add it to the context, EF migrations can “see” it and add it to the database.

Advertisements

Written by Jim McMullen

February 19, 2013 at 3:41 pm

Posted in How-To

Tagged with

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: