Entity Framework, Code First and One-to-Many relat

2019-01-26 17:53发布

问题:

I am using VS 2010 and Entity Framework code first (version 6). I have two entities each in its own context and I want to create a one-to-many relationship between them.

Context 1 has the following entity:

public class MyTrust
{
    public int MyTrustID { get; set; }
    public string MyTrustName { get; set; }
}

and Context 2 has the following entity:

public class MyLocation
{
    public int MyLocationID { get; set; }
    public int MyTrustID { get; set; }
    public virtual MyTrust MyTrust { get; set; }
}

with the following Fluent API

modelBuilder.Entity<MyLocation>()
    .HasRequired(m => m.MyTrust);

The migration file for Context 2 contains the correct keys but also creates a new table for MyTrust which already exists in the other context.

I know that I can edit the migration file but that is not a solution.

My question is, how to I stop the creation of the second MyTrust table.

UPDATE

There was a major flaw above in that I pasted the wrong code into Context 2. Now corrected. Apologies.

回答1:

You are working with so-called bounded contexts. The benefit of such contexts and how to work with them is explained in this blog by Julie Lerman.

The problem you experience, none of the contexts can be used in migrations, is addressed in this part:

If you’re doing new development and you want to let Code First create or migrate your database based on your classes, you’ll need to create an “uber-model” using a DbContext that includes all of the classes and relationships needed to build a complete model that represents the database.

Note that you can share the MyTrust type between all contexts, if you observe these rules (from Lerman & Miller's book DbContext, p 233):

  • An entity can only be attached to one context at a time. This architecture works best with short-lived contexts where the instance to be shared will be completely disassociated from one context before it is attached to another.
  • Entities that are attached to different contexts cannot be attached to one another.

UPDATE

In EF6 you can use multiple contexts for one migration path. See this walkthrough.