[英]Child is used by different parents in one to one relation
Assuming I have a child假设我有一个孩子
public class Child
{
public int Id {get; set;}
}
and two parents which using the childs in one to one relations.和两个父母在一对一的关系中使用孩子。 One child should be used only at one parent.一个孩子只能在一位家长那里使用。 But I want to use the child with Id=1 at ParentA and the child with Id=2 at ParentB for example.但我想在 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;}
}
I want the navigation property at the parents if possible.如果可能的话,我想要父母的导航属性。
I know how to configure a one to one relation when having only one parent because then I would have to add a navigation property in the Child
class and would add the configuration in the OnModelCreating
method of my DbContext
implementation.我知道当只有一个父级时如何配置一对一关系,因为这样我就必须在Child
类中添加一个导航属性,并在我的DbContext
实现的OnModelCreating
方法中添加配置。
But for the scenario with 2+ parents I don't know how the configuration in OnModelCreating
should look like.但是对于有 2 个以上父母的情况,我不知道OnModelCreating
中的配置应该是什么样子。
Based on the additional info from the comments that the ParentA
and ParentB
are not mapped to the same table you could implement 2 one-to-one relationships resulting in:根据ParentA
和ParentB
未映射到同一个表的评论中的附加信息,您可以实现2个一对一关系,从而导致:
public class Child
{
public int Id {get; set;}
public ParentA A {get; set;}
public ParentB B {get; set;}
}
This would mean that when A is initialized B is null and vice versa.这意味着当 A 被初始化时 B 为空,反之亦然。
Alternatively if ParentA and ParentB are similar enough and it makes sence to have a common inheritance:或者,如果 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 { }
And have the one-to-one relationship mapped between Parent
and Child
并在Parent
和Child
之间建立一对一的关系
This might also require DB changes.这可能还需要更改数据库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.