Is there a way to let two children objects reference the same base object using inheritance?

asp.net-core c# entity-framework-6

Question

I want to save a derived object at my DB with the foreign key of an existing base object. Is it even possible? I have something like this:

public class Base
{
    public int BaseId { get; set; }
}

[Table("ChildA")]
public class ChildA : Base
{
    /*...*/
}

[Table("ChildB")]
public class ChildB : Base
{
    /*...*/
}

I have an existing ChildA and I want to create ChildB with the same BaseId as ChildA. The problem is that EntityFramework wont let me do this. If I try to save ChildB passing an existing BaseId, a new Base is created. I understand this is the principle of inheritance but can I achieve what I described?

1
0
1/31/2019 5:27:22 PM

Accepted Answer

Inheritance implies an "is-a" relationship, not a "has-a" relationship, and this is exactly how EF models it at the database level. A derived type will have a one-to-one foreign key created with its base type. As such, you cannot have multiple derived items utilize the same base item, as that would violate referential integrity.

Long and short, if you want to "share" base item, it should not be a base item at all, but rather added via composition:

public class ChildA
{
    public Base Base { get; set; }
}

public class ChildB
{
    public Base Base { get; set; }
}

Obviously, you'd want to change the class names at that point, since they don't really make sense anymore.

0
1/31/2019 6:34:09 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow