2015-04-12 69 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分别在分公司的员工表 –