EF6 Code First Migration with single database multiple context

Viewed 1742

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?

1 Answers
Related