1

我对 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 中创建双向关系?我已经阅读了一些示例,但我对最好的方法感到困惑。

谢谢。

4

2 回答 2

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

这解决了问题。

于 2013-08-20T13:28:10.400 回答
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; }
}
于 2013-08-20T09:16:54.297 回答