[英]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
中的配置應該是什么樣子。
根據ParentA
和ParentB
未映射到同一個表的評論中的附加信息,您可以實現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 { }
並在Parent
和Child
之間建立一對一的關系
這可能還需要更改數據庫。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.