使用现有嵌套实体保存新的断开连接的实体而不复制现有实体

Saving a new disconnected entity with an existing nested entity without duplicating the existing entity

这是我的模型:

public class Place
{
    public int ID { get; set; }
    public virtual ICollection<AddressLine> AddressLines { get; set; }
}
public class AddressLine
{
    public int ID { get; set; }
    public int Order { get; set; }
    public string Value { get; set; }
    public virtual Place Place { get; set; }
    public virtual ICollection<AddressLineType> AddressLineTypes { get; set; }  
}
public class AddressLineType
{
    public int ID { get; set; }
    public string Value { get; set; }
    public virtual ICollection<AddressLine> AddressLines { get; set; }

}

使用 EF6 创建新的 Place 实体时,我必须使用分离的实体,我无法通过传递对上下文的引用来解决它。

我的问题是 PlaceAddressLine 是新的,但 AddressLineType 已经存在。

当我尝试保存 Place 实体时,即使设置了 AddressLineType ID 属性,因为它是分离的,EF 会将其作为新实体插入并因此复制现有 AddressLineType 个条目。

我做了一些研究试图绕过它,发现一篇文章建议最好的方法是将 AddressLineType 添加为 null 并设置外键 属性 这将给出所需的行为。该示例是一对多关系,但我在这里看不到如何为多对多关系执行此操作。

我只是使用实体框架的命名约定来理解映射(我并没有真正接触数据库)。当我建立一对多关系时,我可以看到它会自动添加一个外键,但是这在多对多关系中如何工作?

理想情况下,我希望在创建 Place 的代码中对这个问题进行排序,但我尝试在保存代码中执行以下操作。它不会添加重复数据,但会抛出异常,因为 AddressLineTypes 已经存在。

foreach( var v in place.AddressLines)
{
    foreach (var v2 in v.AddressLineTypes)
    {
        db.AddressLineTypes.Attach(v2);
    }

}

如何在将断开连接的实体添加到上下文并保存之前显示该关系?

您需要为断开连接的实体手动修改状态以像这样更新记录-

    foreach( var v in place.AddressLines)
    {
        foreach (var v2 in v.AddressLineTypes)
        {
            db.Entry<AddressLineTypes>(v2).State = EntityState.Modified;
        }        
    }

if the entity being added has references to other entities that are not yet tracked then these new entities will also be added to the context and will be inserted into the database the next time that SaveChanges is called.

https://msdn.microsoft.com/en-in/data/jj592676.aspx