Enable Migrations with Context in Separate Assembly?

前端 未结 4 1765
礼貌的吻别
礼貌的吻别 2020-11-29 18:59

I have one project that I want to run my update-database against but I have my Models and Context in a separate project.

If I run enable-migration

4条回答
  •  春和景丽
    2020-11-29 19:41

    I had the same problem, and I'm using EntityFramework 4.3.1. It seems that EF6 solves this issue (according to the answer by @SOfanatic) but I didn't want to upgrade to EF6 because of some breaking changes (in the DataAnnotations, for example).

    So, what I did to solve this (and what I learned in the process):

    1. Create a new solution (empty project) and add the project where you have the model you want to enable migrations for (in your case MyProject.MVC). You may need to install the required NuGet packages for it before you are able to add the existing project.

    2. Add a config file with a connection string (don't worry, this is only to trick the migrations engine). Copy your existing database to the model project output folder (should be MVC\bin\Debug in your case). Make sure the connection string in the config file points to that database:

      
          
        
      
    3. Since you are in a new solution, set your model project as a startup project (you can remove the default project).

    4. Run the enable-migrations command in the package manager console. It should create a Migrations folder with two files: a Configuration.cs and a timestamped InitialCreate.cs file. It's nice to have the InitialCreate, that's why you put your existing database in the model project's output folder (but this is optional).

    5. Reload your original solution so that these changes are updated.

    What I learned (as far as I understand):

    1. The migrations engine needs something that looks like a valid connection to work. I was creating my connection string in code (in another project) and that didn't work. I just gave the Migrations engine a "valid" connection string to make it work.
    2. Put your database where the migrations engine can find it (aka model project's output folder) so it creates a starting point for migrations. This starting point is basically your database schema written in the migrations API.
    3. You can restore everything to your previous state once the migrations are set in place, and it works ok.
    4. Everytime you want to manually add a migration, you must "trick" the migrations engine again, just like the first time. I haven't tried with automatic migrations, by I guess this approach works as well.

    By th way, I am using a SQL Server CE 4.0 database, so some things about the connection string have a little twist compared to a standard SQL Server DB or LocalDB. Besides that, everything's the same.

    Hope this is helpful and gives you some insight. Please comment if you know more about the way this migrations work.

提交回复
热议问题