简体   繁体   English

实体框架一对一

[英]Entity Framework multiple One to One

I would like to use code first entity framework to setup a parent entity two instances of a child entity, each with a one to one relationship. 我想使用代码优先实体框架来设置一个父实体的两个子实体实例,每个实例具有一对一的关系。

I tried using the following models:- 我尝试使用以下模型:-

public class Parent
{
    [Key]
    public int Id { get; set; }

    public virtual Child FirstChild { get; set; }

    public virtual Child SecondChild { get; set; }
}

public class Child
{
    [Key, ForeignKey("Parent")]
    public int ParentId{ get; set; }

    public Parent Parent { get; set; }
}

However when I try to add a child to a parent I get the following exception:- 但是,当我尝试将孩子添加到父母时,出现以下异常:-

context.Add(new Parent
{
    FirstChild = new Child(),
    SecondChild = new Child()
});
context.SaveChanges();

System.Data.Entity.Infrastructure.DbUpdateException : Conflicting changes detected. System.Data.Entity.Infrastructure.DbUpdateException:检测到冲突的更改。 This may happen when trying to insert multiple entities with the same key. 尝试使用相同的键插入多个实体时,可能会发生这种情况。

I assume this means that the code is attempting to set both FirstChild and SecondChild to use the same Id as the Parent Id, which is invalid as they can't both have the same Primary Key. 我认为这意味着代码正在尝试将FirstChild和SecondChild设置为使用与父ID相同的ID,这是无效的,因为它们不能具有相同的主键。 Is there a way to configure the models to allow two One to One links? 有没有一种方法可以配置模型以允许两个一对一链接?

What you desire is NOT a one to one mapping. 您想要的不是一对一的映射。 If you think deeply is a one to TWO mapping. 如果您深思是一对二的映射。 In order to have this working in EF, you need to map as a one to many relation and hide the collection property from external usage. 为了使此功能在EF中有效,您需要映射为一对多关系,并在外部使用中隐藏collection属性。

public class Parent
{
    [Key]
    public int Id { get; set; }

    protected virtual List<Child> Children {get; set;}

    [NotMapped]
    public Child FirstChild 
    { 
         get{ return Children[0]; }
         set{ Children[0] = value; } 
    }

    [NotMapped]
    public Child SecondChild 
    { 
         get{ return Children[1]; }
         set{ Children[1] = value; } 
    }
}

public class Child
{
    [Key, ForeignKey("Application")]
    public int ApplicationId { get; set; }

    [Key, ForeignKey("Parent")]
    public int ParentId { get; set; }
    [Key]
    public int Id { get; set; }

    public Parent Parent { get; set; }
}

You may need to map this using the ModelBuilder configuration because the Attributes are not strong enough for this. 您可能需要使用ModelBuilder配置对此进行映射,因为属性对此不够强大。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM