Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF6 Code First Migration with single database multiple context

I'm building an Asp.net MVC5 + EF6 solution with 3 projects. I have enabled automatic migration in my project. The below diagram shows my project structure.

enter image description here

  1. I have a main project and two sub projects.
  2. I have a BaseContext in a main project.
  3. Sub project has their own context classes which derives from BaseContext.
  4. All above contexts are connecting to one database.

Models:

A Model in Project2

public class Product
{
    [Key]
    public int ProductId {get;set;}
    ...
}

A Model in Project3

public class Order
{
    [Key]
    public int OrderId {get;set;}

    [ForeignKey("Product")]
    public int ProductId {get;set}

    public virtual Product Product;

    ...
}

An property from Project3 entity (Order.ProductId) references a property from Project2 entity (Product.ProductId) as a foreign key reference.

When I run update-databasecommand in project 1 & 2 everything is going well. But when run update-database command in project 3 It gives an error:

There is already an object named 'Product' in the database.

Right now I'm using update-database -script command to generate script and manually altering the script. But when project grows, it becomes a difficult task to alter sql scripts each and every time.

I ignored the Product entity by adding modelBuilder.Ignore<Product>() inorder to skip table creation for Productentity, in Project3, but it's ignores the entire relationship.

How can I solve this issue?

like image 986
Rahul Avatar asked Oct 17 '22 07:10

Rahul


1 Answers

You can't do this. One context == one database. When you run a migration against a database for a particular context, it will be based on that context, and will remove any non-applicable tables or try to drop and recreate the database.

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

Alternatively, you can sort of do what you want by going with an existing database approach. Essentially, you turn off migrations entirely on your base context, and then each sub context can then only include the entities that belong to it. However, you're going to be completely responsible for managing the database, yourself, at that point.

public class BaseContext : DbContext
{
    public BaseContext()
        : base("ConnectionString")
    {
        Database.SetInitializer<BaseContext>(null);
    }
}
like image 159
Chris Pratt Avatar answered Oct 21 '22 01:10

Chris Pratt