开发者

One-to-many mappings in one entity 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> Gr开发者_Python百科oups { 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 project, I get this error:

"Invalid column name 'GroupGroupID'. "** and **Navigation property 'MainGroups' of 'Parand.DataAccess.Group' cannot be the inverse of itself.

I want define tree of Group (n layers of groups)

How can I do that it?


This will create the self referencing association in the Group entity:

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

The many to many association between Group and GroupType will be created using a join table so you should remove GroupTypeID property from the Group entity since it will be treated merely as a scalar property and not a Foreign key for this association.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜