2015-04-12 103 views
0

我有那些2種型號如何查詢對一個多對多的關係,與實體框架6

public class BranchEmployees 
{ 
    public int ID { get; set; } 

    [Required, Column(Order = 0), Key] 
    public string ApplicationUserID { get; set; } 

    [Required, Column(Order = 1), Key] 
    public int BranchID { get; set; } 

    public virtual ICollection<ApplicationUser> ApplicationUser { get; set; } 

    public virtual ICollection<Branch> Branch { get; set; } 
} 



public class Branch 
{ 
    public int ID { get; set; } 

    public string BranchName { get; set; } 

    [Required] 
    public string ApplicationUserID { get; set; } 

    public ApplicationUser User { get; set; } 

    public virtual ICollection<BranchEmployees> BranchEmployees { get; set; } 
} 

public class ApplicationUser 
{ 
    //rest of the code 
} 

UPDATE 我把一切都建立了,但我想要的是讓我其僱員查詢ID在分支僱員表中 ,我首先使用實體​​框架代碼與MVC 5,我該怎麼做?

+0

您是否使用代碼優先來創建數據庫? –

+0

@MartinShishkov是的,我確實 –

回答

1

假設你ApplicationUser類將有一個導航屬性調用BranchEmployees,這裏是讓我ID分別在分公司的員工表

List<ApplicationUsers> employeeNames = 
       dbContext 
       .ApplicationUsers 
       .Where(au => au.BranchEmployees 
           .Count() > 0).ToList(); 

而且職工的查詢,可以爲您提供整個模型包括ApplicationUser ?我也想知道爲什麼你不喜歡BranchEmployees從ApplicationUser繼承。

+0

此做了僱員技巧,謝謝,但您是從ApplicationUser繼承的意思是什麼? –

+0

真棒!如果每個'BranchEmployee'也是'ApplicationUser'和共享許多基本屬性,那麼是的,我的意思吧。 – renakre

+0

哦,是的,謝謝,我會考慮這一點 –

0

你並不需要一個類,它指示兩個表之間的許多一對多的關係,當你做代碼優先。這裏的關鍵是創建這些類的virtual屬性。可以說你有一個class Studentclass CourseStudents可以在很多CoursesCourses可以有很多Students。要生成使用這些模型類應該是這樣的數據庫:

public class Student 
    { 
     private ICollection<Course> _courses; 

     public Student() 
     { 
      this._courses = new HashSet<Course>(); 
     } 

     [Key] 
     public int Id { get; set; } 

     public string FullName { get; set; } 

     public virtual ICollection<Course> Courses 
     { 
      get { return this._courses; } 
      set { this._courses = value; } 
     } 
    } 

而對於Course

public class Course 
{ 
    private ICollection<Student> _students; 

    public Course() 
    { 
     this._students = new HashSet<Student>(); 
    } 

    [Key] 
    public int Id { get; set; } 

    public string Name { get; set; } 

    public string Description { get; set; } 

    public virtual ICollection<Student> Students 
    { 
     get { return this._students; } 
     set { this._students = value; } 
    } 
} 

我希望這可以幫助您解決您的問題。

+0

其實也沒什麼,我更新的問題,以顯示第三類,我把一切都建立了,但我想要的是讓我查詢ID分別在分公司的員工表 –