实体框架,跨多个上下文的代码优先和一对多关系 [英] Entity Framework, Code First and One-to-Many relationship across multiple contexts

查看:79
本文介绍了实体框架,跨多个上下文的代码优先和一对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我首先使用VS 2010和Entity Framework代码(版本6)。我在各自的上下文中有两个实体,我想在它们之间创建一对多关系。

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.

上下文1具有以下实体:

Context 1 has the following entity:

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

并且上下文2具有以下实体:

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; }
}

具有以下Fluent API

with the following Fluent API

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

上下文2的迁移文件包含正确的键,但还为<$ c $创建了一个新表c> 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.

我的问题是,如何停止第二个 MyTrust 表的创建。

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

更新

上面有一个主要缺陷,就是我将错误的代码粘贴到了上下文2中。现在已更正。抱歉。

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

推荐答案

您正在使用所谓的绑定上下文。 Julie Lerman在此博客中解释了此类上下文的好处以及如何使用它们

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:


如果您正在进行新开发,并且想让Code First根据您的类创建或迁移数据库,则需要使用以下命令创建超级模型 DbContext,其中包含构建代表数据库的完整模型所需的所有类和关系。

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.

请注意,您可以共享如果您遵守以下规则(在Lerman& Miller的书 DbContext ,第233页),则在所有上下文之间输入 MyTrust 类型:

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



  • 一次只能将一个实体附加到一个上下文。这种架构最适合
    的短期生存环境,在这种情况下,要共享的实例在连接到另一个环境之前将完全从一个环境中分离出


更新 >

在EF6中,您可以将多个上下文用于一个迁移路径。参见本演练

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

这篇关于实体框架,跨多个上下文的代码优先和一对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆