I'm having some difficulty getting my two contexts that use the same database to cooperate. Here's the scenario:
In an MVC application using EF 6 Code-First, there is one database with two contexts. - The first context is the ApplicationIdentity context with a customized ApplicationUser object. - The second context is the business context, which holds a Team model:
public class Team
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public ApplicationUser TeamLeader { get; set; }
public string Name { get; set; }
public virtual ICollection<ApplicationUser> TeamMembers { get; set; }
public bool IsActive { get; set; }
}
Managing the migrations has been difficult, though this answer has proven extremely helpful: Multiple DB Contexts in the Same DB and Application in EF 6 and Code First Migrations
The problem is that the Identity context keeps trying to create the Team table in it's migrations, and then the Business context keeps trying to create duplicate ApplicationUser records when a new team is created, populated, and saved.
What I would like is for the following rules to be applied:
Does anyone have any tips on how to get these contexts to play nice with each other? I really don't want to break the referential integrity between Identity objects and business objects.
Multiple DbContext was first introduced in Entity Framework 6.0. Multiple context classes may belong to a single database or two different databases. In our example, we will define two Context classes for the same database. In the following code, there are two DbContext classes for Student and Teacher.
In this tutorial, you: 1 Create an MVC web app 2 Set up the site style 3 Install Entity Framework 6 4 Create the data model 5 Create the database context 6 Initialize DB with test data 7 Set up EF 6 to use LocalDB 8 Create controller and views 9 View the database More ...
Create the database context. The main class that coordinates Entity Framework functionality for a given data model is the database context class. You create this class by deriving from the System.Data.Entity.DbContext class. In your code, you specify which entities are included in the data model.
A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship. I've taken a really careful look at the entity which looks normal.
What you're trying to do looks like "DDD Bounded Contexts".
It's a bit long to explain how to use them, but here are some tips:
modelBuilder.Ignore<EntityType>();
to exclude from your model related entities that are automatically added to your contextmodelBuilder
to configure themThis is a very interesting post by Julie Lerman: Data Points - Shrink EF Models with DDD Bounded Contexts
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