Entity Framework Code First Self-Referencing Relationship RRS feed

  • Question

  • Hi, 

    I experience an issue when using self referencing with code first.

    public class Group{

    public Group() {           
                this.Children = new HashSet<Group>();

            public System.Guid GroupId { get; set; }

    public Guid ParentId { get; set; }
            public virtual Group Parent { get; set; }
            public virtual ICollection<Group> Children { get; private set; } //immediate children


    A group may have one parent group and many children group.

    And try configuration as below:

    this.HasOptional(g => g.Parent).WithMany(g => g.Children).HasForeignKey(g => g.ParentId);
    this.HasMany(g => g.Children).WithOptional(g => g.Parent).HasForeignKey(g => g.ParentId);

    Always get exception:

    \tSystem.Data.Entity.Edm.EdmAssociationType: : Multiplicity conflicts with the referential constraint in Role 'Group_Parent_Target' in relationship 'Group_Parent'. Because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be '1'.

    Could anyone please help me out?



    • Moved by Kristin Xie Thursday, September 10, 2015 7:38 AM move to appropriate forum
    Wednesday, September 9, 2015 11:49 PM


All replies