Bi-directional relationships in Entity Framework (Code First)

回眸只為那壹抹淺笑 提交于 2019-12-11 07:54:19

问题


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.


回答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; }
}



回答2:


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.



来源:https://stackoverflow.com/questions/18331231/bi-directional-relationships-in-entity-framework-code-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!