Yahya Hussein
Yahya Hussein

Reputation: 9121

EF 6 getting parent record from DB when table has many to many relation with itself

I am trying to build an organization hierarchy where each team might contain one or many members and/or one or many sub-teams.

To do so, my model is:

 public class Team
 {
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Employee> Members { get; set; }
    public virtual ICollection<Team> SubTeams { get; set; }
    public Employee Manager { get; set; }
 }

When adding a migration and updating database, everything seems logical in the table. EF has added an extra nullable column "Team_Id" where the Id of the parent Team gets stored.

Table Screenshot

My question is about getting the Id of the parent Team from my model. I tried adding:

public int? Team_Id 

To my model, but EF considered it as a model change and asked for another migration.

How can I get the value of column Team_Id in my model? getting this info takes too much processing when looping through teams.

Upvotes: 0

Views: 33

Answers (1)

Saeid Amini
Saeid Amini

Reputation: 1307

I always add foreign key in my model. When it adds to the model, EF won't add Team_Id .

public class Team
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Employee> Members { get; set; }
    public virtual ICollection<Team> SubTeams { get; set; }
    public Employee Manager { get; set; }

    public int? ParentId { get; set; }
    [ForeignKey("ParentId")]
    public Team ParentTeam { get; set; }
}

I hope this example be helpful.

Upvotes: 1

Related Questions