简体   繁体   中英

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.

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.

But for the scenario with 2+ parents I don't know how the configuration in OnModelCreating should look like.

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:

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.

Alternatively if ParentA and ParentB are similar enough and it makes sence to have a common inheritance:

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

This might also require DB changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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