Blake Rivell
Blake Rivell

Reputation: 13875

Table not added to database when adding a new migration using entity framework 7

I am working with the latest ASP.NET Core 1.0 and EF7.

I created a new ASP.NET Core 1.0 MVC Web application from scratch and running the initial migration was simple:

dnx ef migrations add Initial
dnx ef database update 

(I don't think I needed to run this database update command but did anyway)

Additionally I have the following as the constructor of my DbContext which I don't think I need either:

public ApplicationDbContext()
{
     Database.EnsureCreated();
}

After creating the Initial migration I noticed that a table for any DbSet in my DbContext was added to the database.

Now I simply added one more model, and added one more DbSet for that model in my DbContext and ran the following:

dnx ef migrations add BookMigration
dnx ef database update

When calling database update I noticed migrations tries to run and create tables for all migrations everything rather than just applying only my new migrations.

Is this a bug? How can I prevent this?

Upvotes: 3

Views: 3691

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239200

I'm not overly familiar with EF7 myself yet, but your question intrigued me, as it seems like you're doing everything right. However, based on what I know from previous versions of EF, the Database.EnsureCreated() line was jumping out at me. A little research later, I think I've found your problem here: http://thedatafarm.com/data-access/ef7-ensurecreated-vs-migrate-methods/

All credit goes to the original author of this post, but for the sake of posterity, I'll summarize here. The meat of the post comes in with a comment by Rowan Miller on a Github issue related to this:

EnsureCreated totally bypasses migrations and just creates the schema for you, you can’t mix this with migrations. EnsureCreated is designed for testing or rapid prototyping where you are ok with dropping and re-creating the database each time. If you are using migrations and want to have them automatically applied on app start, then you can use context.Database.Migrate() instead.

The gist, I think, is that EnsureCreated is the functional equivalent of automatic migrations from previous versions of EF, which also only works if you're not trying to manually migrate. Essentially, it's an either/or thing. Anyways, give the post a good read so you understand all the implications.

Upvotes: 5

Related Questions