【发布时间】:2022-06-10 20:35:05
【问题描述】:
假设我有一个孩子
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 中的配置应该是什么样子。
【问题讨论】:
-
这将不再是一对一的关系,您需要在
Child类中添加一个List<ParentA>导航属性,并在OnModelCreating中使用.WithMany作为@ 987654332@类。 -
@Etheraex 但我不希望孩子被不同的父母使用。而且我不想在子节点上添加导航属性,因为这样我就必须为每个父节点(ParentA 和 ParentB)添加一个导航属性,并且只会设置一个。
-
再看问题,有没有可能是你在这两个类的代码区打错字了。您有 2 个 ParentA 类,而不是 ParentA 和 ParentB 类。这有点让人困惑。因为如果这些是不同的类,你基本上想要 2 个与 Child 有 2 个一对一关系的 Parent 类?
-
@Etheraex 啊...该死的...是的错字。改了
-
好的,这样更容易理解,但这不是一个简单的解决方案。
ParentA和ParentB是否都映射到同一个表?你的数据库是如何设置的?您是否熟悉在 SQL 表中建模对象继承的任何技术:stackoverflow.com/questions/3579079/…