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.
BaseContext
in a main project.context
classes which derives from
BaseContext
. 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-database
command 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 Product
entity, in Project3, but it's ignores the entire relationship.
How can I solve this issue?
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With