实体框架中的双向关系(代码优先)

时间:2013-08-20 09:12:58

标签: entity-framework ef-code-first

我对Code First EF的最佳实践有疑问。 我有两个类User.cs和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;}
}

每个用户都有一个团队。团队需要TeamLead和Manager。如何在Code First EF中创建双向关系?我已经阅读了一些例子,但我对最好的方法感到困惑。

感谢。

2 个答案:

答案 0 :(得分: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; }
}

答案 1 :(得分:1)

只为那些需要知道的人。这是我如何解决它。

我使用Fluent Api方法创建关系:

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

        modelBuilder.Entity<Team>()
           .HasMany(m => m.Users).WithRequired(m => m.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 List<User> Users { get; set; }

用户类:

 [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; }

这解决了这个问题。