我有那两个模特
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
}
更新 我已经设置了所有内容,但我想要的是查询,它让我的员工的ID在分支员工表中 ,我首先使用实体框架代码与MVC 5,我该怎么做?
答案 0 :(得分:1)
假设您的ApplicationUser
类将具有名为BranchEmployees
的导航属性,这里的查询将获取其ID在分支员工表中的员工
List<ApplicationUsers> employeeNames =
dbContext
.ApplicationUsers
.Where(au => au.BranchEmployees
.Count() > 0).ToList();
另外,您能提供包括ApplicationUser在内的整个模型吗?我也想知道为什么你不喜欢BranchEmployees继承ApplicationUser。
答案 1 :(得分:0)
当您执行代码优先时,您不需要一个表示两个表之间多对多关系的类。这里的关键是创建这些类的virtual
属性。假设您有class Student
和class Course
。 Students
可以有多个Courses
,Courses
可以有多个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; }
}
}
我希望这可以帮助您解决问题。