Chris
Chris

Reputation: 373

Bi-directional relationships in Entity Framework (Code First)

I have a question about best practice in terms of Code First EF. I have two classes User.cs and Team.cs:

public class Team()
{
[Key]
public int TeamId{get;set;}
public string TeamName {get;set;}
public virtual User TeamLead {get;set;}
public virtual User Manager {get;set;}
}

  public class User
{
   public int UserId {get;set;}
   public string FullName {get;set;}
}

Each User has one Team. A team needs a TeamLead and a Manager. How do I create the bi-directional relationship in Code First EF? I have read a few examples but I am confused about the best way to do it.

Thanks.

Upvotes: 1

Views: 3395

Answers (2)

Chris
Chris

Reputation: 373

Just for those that need to know. Here is how I solved it.

I used the Fluent Api method of creating the relationships:

  protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<Team>()
           .HasMany(m => m.Users).WithRequired(m => m.Team);
    }

Team class:

  [Key]
    public int TeamId { get; set; }

    public string TeamName { get; set; }

    public virtual User TeamLead { get; set; }

    public virtual User Manager { get; set; }

    public List<User> Users { get; set; }

User class:

 [Key]
    public int UserId { get; set; }

    [Display(Name = "User Name")]
    [Required(ErrorMessage = "User Name is required")]
    public string UserName { get; set; }

    [Display(Name = "Full Name")]
    public string FullName { get; set; }

    [Display(Name = "Email")]
    [Required(ErrorMessage = "Email is required")]
    public string Email { get; set; }

    public virtual Team Team { get; set; }

This solved the problem.

Upvotes: 1

MarcinJuraszek
MarcinJuraszek

Reputation: 125660

public class Team
{
    [Key]
    public int TeamId{get;set;}
    public string TeamName {get;set;}

    [ForeignKey("TeamLead")]
    public int TeamLeadId { get; set; }
    public virtual User TeamLead {get;set;}

    [ForeignKey("Manager")]
    public int ManagerId { get; set; }
    public virtual User Manager {get;set;}
}

public class User
{
    [Key]
    public int UserId {get;set;}
    public string FullName {get;set;}

    [ForeignKey("Team")]
    public int TeamId { get; set; }
    public virtual Team Team { get; set; }
}

Upvotes: 1

Related Questions