2013-08-20 109 views
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和一個經理。如何在Code First EF中創建雙向關係?我已經閱讀了幾個例子,但我對最好的方式感到困惑。

謝謝。

回答

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

嗨,感謝您的回覆。我運行該代碼,並得到以下錯誤:引入表'團隊'上的FOREIGN KEY約束'FK_dbo.Teams_dbo.Users_TeamLeadId'可能會導致循環或多個級聯路徑。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY約束。 無法創建約束。查看以前的錯誤。 – Chris

+0

您可以通過流暢的API修復該錯誤:http://stackoverflow.com/a/17127512/1163867 – MarcinJuraszek

+0

有沒有其他方法可以在不使用Fluent API的情況下執行此操作? – Chris

1

只爲那些需要知道的。這是我如何解決它。

我用創建關係的流暢API方法:

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

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

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

這解決了這個問題。