1

I am trying to do this:

Hibernate: Parent-Child Relationship to Itself

but in ASP.NET MVC 4

here are my 2 models (which i have no clue if this is the correct way to do this):

public class Group
{
    public int GroupID { get; set; }

    [Required]
    [StringLength(50)]
    public string Name { get; set; }

    public virtual ICollection<GroupRelation> GroupRelations { get; set; }
}

public class GroupRelation
{
    public int GroupRelationID { get; set; }

    public int? ParentID { get; set; }

    public int? ChildID { get; set; }


    [ForeignKey("ParentID")]
    public virtual Group ParentGroups { get; set; }

    [ForeignKey("ChildID")]
    public virtual Group ChildGroups { get; set; }
}

Here is my Context(again no clue if this is right):

public class TaskTrackerContext : DbContext
{
    public DbSet<Group> Groups { get; set; }
    public DbSet<GroupRelation> GroupRelations { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Group>()
            .HasMany(g => g.GroupRelations).WithOptional(g => g.ChildGroups).HasForeignKey(g => g.ChildID);
        modelBuilder.Entity<Group>()
            .HasMany(g => g.GroupRelations).WithOptional(g => g.ParentGroups).HasForeignKey(g => g.ParentID);

    }
}

With this setup i get the following in my database:

(i tried to put in a pic or a link to a pic and it wont let me...)

So it makes the 2 relationships i am expecting "PK_GroupID - FK_ParentID" and "PK_GroupID - FK_ChildID", but then it creates an extra column called "Group_GroupID" and makes the following relationship: "PK_GroupID - FK_Group_GroupID".

So what am I doing wrong?

4

0 回答 0