1

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.

Chris
  • 335
  • 4
  • 17

2 Answers2

1
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; }
}
MarcinJuraszek
  • 118,129
  • 14
  • 170
  • 241
  • Hi thanks for the reply. I ran that code and got the following error: Introducing FOREIGN KEY constraint 'FK_dbo.Teams_dbo.Users_TeamLeadId' on table 'Teams' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint. See previous errors. – Chris Aug 20 '13 at 09:24
  • You can fix that error with a fluent API: http://stackoverflow.com/a/17127512/1163867 – MarcinJuraszek Aug 20 '13 at 09:27
  • Is there any other way to do this without using the Fluent API? – Chris Aug 20 '13 at 10:10
1

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.

Chris
  • 335
  • 4
  • 17