gpt4 book ai didi

entity-framework - Entity Framework 、代码优先和跨多个上下文的一对多关系

转载 作者:行者123 更新时间:2023-12-05 01:07:13 32 4
gpt4 key购买 nike

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

上下文 1 具有以下实体:

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

并且上下文 2 具有以下实体:
public class MyLocation
{
public int MyLocationID { get; set; }
public int MyTrustID { get; set; }
public virtual MyTrust MyTrust { get; set; }
}

使用以下 Fluent API
modelBuilder.Entity<MyLocation>()
.HasRequired(m => m.MyTrust);

上下文 2 的迁移文件包含正确的键,但也为 MyTrust 创建了一个新表。已经存在于其他上下文中。

我知道我可以编辑迁移文件,但这不是解决方案。

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

更新

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

最佳答案

您正在使用所谓的有界上下文。此 blog by Julie Lerman 中解释了此类上下文的好处以及如何使用它们。 .

您遇到的问题,所有上下文都不能用于迁移,在这部分解决:

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.



请注意,您可以共享 MyTrust在所有上下文之间键入,如果您遵守这些规则(来自 Lerman & Miller 的书 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.


更新

在 EF6 中,您可以为一个迁移路径使用多个上下文。见 this walkthrough .

关于entity-framework - Entity Framework 、代码优先和跨多个上下文的一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18869068/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com