I'm having quite the issue trying to create a recursive relationship in Entity Framework 6.1.
I'll need some different types of Categories, but have created a "base" abstract class for all of them. I'm using Table-Per-Type hierarchical strategy. A Category may or may not have a ParentCategory. (If not, then it's a top-level category)
In the code below, I'm showing how I've created the abstract Category class and the ParentCategory and ChildCategories navigation properties. I've made the ParentCategoryId nullable, as it's not required in the case of a top-level category. I've seen a few posts that are exactly what I'm trying to achieve here, and although I've think I have all answers addressed, I'm still getting the following error:
Category_ParentCategory: : Multiplicity conflicts with the referential constraint in Role 'Category_ParentCategory_Target' in relationship 'Category_ParentCategory'. Because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be '1'.
I'm wondering if it has something to do with Category being an abstract class and the added inheritance model I'm using as I haven't seen that exact usage in any of the other posts regarding this type of recursive relationship. Any help is appreciated!
public abstract class Category : ICategory
{
protected Category()
{
ChildCategories = new HashSet<Category>();
}
public int CategoryId { get; private set; }
public int? ParentCategoryId { get; set; }
public virtual Category ParentCategory { get; set; }
public virtual ICollection<Category> ChildCategories { get; set; }
}
public class WLCategory : Category, IWLCategory
{
public WLCategory() : base()
{
DynamicFields = new HashSet<DynamicFieldDef>();
}
public virtual ICollection<DynamicFieldDef> DynamicFields { get; set; }
}
Using FluentAPI, I've configured the database creation as such:
class CategoriesConfig : EntityTypeConfiguration<Category>
{
public CategoriesConfig()
{
HasOptional(p => p.ParentCategory).WithMany(p => p.ChildCategories)
.HasForeignKey(p => p.ParentCategoryId);
ToTable("Categories");
}
}
class WLCategoriesConfig : EntityTypeConfiguration<WLCategory>
{
public WLCategoriesConfig()
{
HasKey(p => p.CategoryId);
ToTable("WLCategories");
}
}