I have an entity that has a reference to itself in a parent - child relationship. I need to find out how to implement this using code first and fluent API. Below is my entity class.
public class MenuItem
{
public int Id { get; set; }
public string LinkText { get; set; }
public string ControllerName { get; set; }
public string ActionName { get; set; }
public MenuItem Parent { get; set; }
public int ParentId { get; set; }
private IList<Role> Roles;
private IList<MenuItem> ChildMenuItems;
public MenuItem()
{
Roles = new List<Role>();
ChildMenuItems = new List<MenuItem>();
}
}
I tried using the below code in my entity configuration.
HasOptional(m => m.Parent)
.WithMany(m => m.ChildMenuItems)
.HasForeignKey(m => m.ParentId)
.WillCascadeOnDelete(false);
but I got this error -
One or more validation errors were detected during model generation:
Vantage.Data.EF.MenuItem_Parent: : Multiplicity conflicts with the referential constraint in Role 'MenuItem_Parent_Target' in relationship 'MenuItem_Parent'. Because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be '1'.
All help appreciated.
Thank You.
ParentId field should be nullable. You are not able to create any record if parentid is required.
Just change
public int ParentId { get; set; }
to
public int? ParentId { get; set; }