Entity Framework, Code First, and One-to-Many Structures in Different Contexts

First I use VS 2010 and Entity Framework code (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 object:

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

and context 2 has the following object:

 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 a different context.

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

My question is: how to stop creating a second MyTrust table.

UPDATE

There was a major flaw in that I inserted the wrong code in context 2. Now fixed. Apologies

+4
source share
1 answer

You work with so-called restricted contexts. The benefits of such contexts and how to work with them are explained in this blog by Julie Lerman .

The problem you are facing, none of the contexts can be used in migrations, is considered in this part:

If you are doing a new development and want Code First to create or migrate your database based on your classes, you need to create a "uber-model" using DbContext, which includes all the classes and relationships necessary to create a complete model that represents a database.

Note that you can share the MyTrust type between all contexts if you follow these rules (from the book by Lerman and Miller DbContext, p. 233):

  • An entity can only be bound to one context at a time. This architecture works best under short circuit conditions when the instance to be used is completely disassociated from one context before it is attached to another.
  • Objects attached to different contexts cannot be attached to each other.

UPDATE

In EF6, you can use multiple contexts for the same migration path. See this walkthrough .

+5
source

Source: https://habr.com/ru/post/1502777/


All Articles