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?
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.