EF6 Code first “model backing DataContext has chan

2019-06-07 09:32发布

问题:

I'm new to the code first methodology.

I'm getting this error:

"The model backing the 'DataContext' context has changed since the database was created. Consider using Code First Migrations to update the database".

I have a WPF app using EF6 & MVVM running against a local db (.mdf life).

I created a new model, called langauges then I added a new DbSet< langauges > collection to my datacontext.

When the code tries to instantiate the a datacontext object, I get the error above.

What am I missing? For all my other new tables/models I could just create them in code, run a test method to create a record in the new table/model and then EF code first would automatically create the new table and add the entry with complaining. Why won't it work now?

回答1:

By default EF6 code first will not recreate your database. It says so in the exception. It also comes with the solution to your problem. You need to use Code First Migrations

Open your PackageManager Console and type in the following

  1. Enable-Migrations
  2. Add-Migration {Name} (this will create a class with the changes For the first I always use Init as name so it is easy to go back to the initial state)
  3. Update-Database (this will update your database)

More information can be found on MSDN