MVC / Entity Code-First Multiple Contexts with Referential Integrity between them

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
    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:

  • The IdentityContext is responsible for creating and altering the schema of the Identity tables only. It has no knowledge of objects (aka Team) outside of it's area of responsibility.
  • The Business Context is responsible for referential integrity between it's objects and the IdentityObjects, but it may not edit records in the Identity tables. If a user does not exist, error, don't create.

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.


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:

  • use modelBuilder.Ignore<EntityType>(); to exclude from your model related entities that are automatically added to your context
  • use different classes in each model where necessary, and map them appropriately. I mean classes that map only part of the columns. Use modelBuilder to configure them
  • use readonly navigation properties and readonly properties where necessary

This is a very interesting post by Julie Lerman: Data Points - Shrink EF Models with DDD Bounded Contexts

Need Your Help

How to set the date-time in the form for twitter-bootstrap

jquery css html5 date twitter-bootstrap

I am using the twitter bootstrap and I need to set the input as date-time for one of the labels in the form and I am not sure how to do it..

Passing URL parameters to a ClickOnce application in any browser

.net url deployment clickonce

I have a ClickOnce application, and I need the ability to pass URL parameters to it. For example, a user could click a URL of the form "", and this will