Hi I've run into a problem with Parent/Child Relations between abstract baseclasses and their implementations
public class SuperParent
{
public ICollection<Parent> ParentList { get; set; }
}
public abstract class Parent
{
public int Id { get; set; }
public string Title { get; set; }
}
public abstract class ParentExtended : Parent
{
public ICollection<ChildClass> ChildClassList { get; set; }
}
public class RealClass : ParentExtended
{
}
public class ChildClass
{
public int Id { get; set; }
public Parent Parent { get; set; }
}
DBContext looks as follows:
public DbSet<SuperParent> SuperParents { get; set; }
public DbSet<Parent> Parents { get; set; }
public DbSet<ChildClass> ChildClasses { get; set; }
Example code
SuperParent sp = new SuperParent();
sp.ParentList = new List<Parent>();
RealClass parent = new RealClass();
parent.ChildClassList = new List<ChildClass>();
parent.ChildClassList.Add(new ChildClass());
sp.ParentList.Add(parent);
Results in the database table ChildClass with columns
- Id
- Parentid(FK)
- ParentExtendedId(FK)
where ParentId is always null, parentExtendedId is filled with the correct Id but unwanted.
My question is this the way to go and how can i give childclass Parent as a parent and not ParentExtended
I found the answer myself and it's rather easy:) Decorate the childlist in the abstract class ParentExtended with a data annotation that tells the class what the inverse property within the child is.
So in my example:
With creates a pointer to back to Realclass but in the variable named Parent