I have a problem when defining a model in EF5. I want make the ParentId as a Foreign Key in the database but I’m getting an error:
System.Data.Entity.Edm.EdmAssociationType: : Multiplicity conflicts with the referential constraint in Role ‘Category_Parent_Target’ in relationship ‘Category_Parent’. Because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be ‘1’.
Here is my Model:
public class Category
{
public Category()
{
this.Childs = new HashSet<Category>();
}
public int CategoryId { get; set; }
public string Name { get; set; }
public int ParentId { get; set; }
public virtual Category Parent { get; set; }
public virtual ICollection<Category> Childs { get; set; }
}
and
modelBuilder.Entity<Category>()
.HasOptional(c => c.Parent)
.WithMany(c => c.Childs)
.HasForeignKey(d => d.ParentId);
If a
Categorymay or may not have aParent, then theParentIdmay or may not have a value.So, make
ParentIdnullable: