First migration of EF6 code with multiple contexts with one database

I am creating an MVC5 + EF6 solution with 3 projects. I have enabled automatic migration in my project. The diagram below shows my project structure.

enter image description here

  • I have a main project and two sub projects.
  • I have BaseContext

    a main project.
  • The sub project has its own classes context

    that come from BaseContext

  • All of the above contexts connect to the same database.


Model in Project2

public class Product
    public int ProductId {get;set;}


Model in Project3

public class Order
    public int OrderId {get;set;}

    public int ProductId {get;set}

    public virtual Product Product;



The object's Project3 ( Order.ProductId

) property refers to a property from the Project2 object (Product.ProductId)

as a foreign key reference.

When I run the command update-database

on projects 1 and 2 everything goes well. But when I run the command update-database

in project 3, I get an error message:

The database already has an object named "Product".

I am currently using a command update-database -script

to generate a script and manually modify the script. But as the project grows, it becomes difficult to change the sql scripts every time.

I ignored the object Product

by adding an modelBuilder.Ignore<Product>()

inorder to skip creating a table for the object Product

in Project3, but it ignores all relationships.

How can I solve this problem?


source to share

1 answer

You cannot do this. One context == one database. When you migrate across a database for a specific context, it will be based on that context and will drop any irrelevant tables or try to drop and recreate the database.

You should move all of your entities into a class library, along with one instance of the context that includes all of them. Then you can migrate against the class library and just reference in other projects.

Alternatively, you can do what you want by going with your existing database approach. Basically, you turn off migrations completely in your base context, and then each additional context can only include objects that belong to it. However, you will be solely responsible for managing the database at this time.

public class BaseContext : DbContext
    public BaseContext()
        : base("ConnectionString")




All Articles