繁体   English   中英

孩子被不同的父母以一对一的关系使用

[英]Child is used by different parents in one to one relation

假设我有一个孩子

public class Child
{
    public int Id {get; set;}
}

和两个父母在一对一的关系中使用孩子。 一个孩子只能在一位家长那里使用。 但我想在 ParentA 使用 Id=1 的孩子,在 ParentB 使用 Id=2 的孩子。

public class ParentA
{
    public int Id {get; set;}
    public int ChildId {get; set;}
    public Child Child {get; set;}
}

public class ParentB
{
    public int Id {get; set;}
    public int ChildId {get; set;}
    public Child Child {get; set;}
}

如果可能的话,我想要父母的导航属性。

我知道当只有一个父级时如何配置一对一关系,因为这样我就必须在Child类中添加一个导航属性,并在我的DbContext实现的OnModelCreating方法中添加配置。

但是对于有 2 个以上父母的情况,我不知道OnModelCreating中的配置应该是什么样子。

根据ParentAParentB未映射到同一个表的评论中的附加信息,您可以实现2个一对一关系,从而导致:

public class Child
{
    public int Id {get; set;}
    public ParentA A {get; set;}
    public ParentB B {get; set;}
}

这意味着当 A 被初始化时 B 为空,反之亦然。

或者,如果 ParentA 和 ParentB 足够相似并且有共同的继承是有意义的:

public class Child
{
    public int Id {get; set;}
    public Parent {get; set;}
}

public class Parent
{
    public int Id {get; set;}
    public int ChildId {get; set;}
    public Child Child {get; set;}
}

public class ParentA : Parent { }

public class ParentB : Parent { }

并在ParentChild之间建立一对一的关系

这可能还需要更改数据库。

暂无
暂无

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

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