One-to-Many Mappings in One Object in EF First Code

I have 2 classes:

public class GroupType
{
    [Key]
    public decimal GroupTypeID   { get; set; }
    public string  Title         { get; set; }

    public virtual ICollection<Group> Groups { get; set; }
}

and

public class Group
{
    [Key]
    public decimal          GroupID          { get; set; }
    public string           Title            { get; set; }
    public decimal?         GroupParentID    { get; set; }
    public decimal          GroupTypeID      { get; set; }
    public string           FileName         { get; set; }
    public string           GroupCode        { get; set; }

    public virtual ICollection<GroupType> GroupTypes { get; set; }
    public virtual ICollection<Group> MainGroups { get; set; }
}

when I debug a project, I get this error:

"Invalid column name 'GroupGroupID'." ** and ** Properties of the navigation 'Main groups' 'Parand.DataAccess.Group' cannot be reversed by itself.

I want to define a group tree ( n group layers)

How can i do this?

+3
source share
1 answer

This will create a self-reference association in the object Group:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Group>()
                .HasMany(g => g.MainGroups)
                .WithOptional()
                .HasForeignKey(p => p.GroupParentID);
}

Group GroupType , GroupTypeID Group, , .

+2

Source: https://habr.com/ru/post/1793227/


All Articles