简体   繁体   English

如何使用实体框架查询多对多关系

[英]How to query many to many relation using Entity Framework

I have the following models in my application: 我的应用程序中具有以下模型:

public class Employee
{
    public int PersonId { get; set; }
    public string  FirstName { get; set; }
    public string LastName { get; set; }
    public int Benefits { get; set; }
}

public class Department
{
    public int DeptID { get; set; }
    public string DeptName { get; set; }
}

public class DeptEmp
{
    public int PersonID { get; set; }
    public int DeptID { get; set; }
}

I want to create a query, using Entity Framework, to select all columns from employee with a condition that it retrieves only those employees that PersonId has a relation with DeptId in the DeptEmp class and DepartId from Department has a relation with DeptId in the DeptEmp . 我想创建一个查询,使用实体框架,选择从所有列employee与它检索只有那些员工的条件PersonId有关系DeptIdDeptEmp类和DepartIdDepartment有关系DeptIdDeptEmp

I have written the following LINQ statement: 我写了以下LINQ语句:

var selectEmployees = from e in Employee
                      join d in DeptEmp on e.PersonId equals d.PersonId
                      join dd in Depatment on d.DeptId equals dd.DeptId
                      select new
                         {
                             e.FirstName,
                             e.LastName,
                             e.Benefits
                         };

but it is not working. 但它不起作用。 Am I missing anything? 我有什么想念的吗?

Entity framework works on a "use standards or else" basis. 实体框架在“使用标准或其他”基础上工作。 It is fairly easy if you use standards, if not you have to provide lots of information about your deviations. 如果使用标准,这是相当容易的,否则,您必须提供许多有关偏差的信息。

For instance, entity framework expects a primary key of Employee as Id or EmployeeId. 例如,实体框架期望Employee的主键为Id或EmployeeId。 If you decide to use a different primary key (PersonId), you'll have to tell entity framework that this is your primary key. 如果决定使用其他主键(PersonId),则必须告诉实体框架这是您的主键。

The same is with your many-to-many relationship. 您的多对多关系也是如此。 If you use the defaults it is fairly easy, otherwise you'll need attributes or fluent API to inform about the deviations from the defaults. 如果使用默认值,则非常容易,否则,您将需要属性或流利的API来告知与默认值的差异。

Default many-to-many in your Employee / Department model would be: 您的员工/部门模型中的默认多对多为:

See also Entity Framework Tutorial Configure many-to-many 另请参见实体框架教程配置多对多

public class Employee
{
    public int EmployeeId{ get; set; }

    public string  FirstName { get; set; }
    public string LastName { get; set; }
    public int Benefits { get; set; }

    // an employee has many departments:
    public virtual ICollection<Department> Departments { get; set; }
}

public class Department
{
    public int DeptartmentId { get; set; }
    public string DeptName { get; set; }

    // an department has many employees
    public virtual ICollection<Employee> Employees{ get; set; }
}

public MyDbContext : DbContext
{
    public DbSet<Employee> Employees {get; set;}
    public DbSet<Department> Departments {get; set;}
}

If you make a simple console application with these classes you'll see that it creates also a many-to-many table. 如果使用这些类制作一个简单的控制台应用程序,您会发现它还会创建一个多对多表。 You'll seldom need this table, but if you really need it, you could add it to the DbContext. 您很少需要该表,但是如果确实需要它,可以将其添加到DbContext中。

I want ... to select all columns from employee with the condition that it retrieves only those employees that PersonId has a relation with DeptId 我想...从雇员中选择所有列,条件是它仅检索PersonId与DeptId有关系的那些雇员

I assume that this means that given a DeptId you want all properties from all employees working in this DeptId: 我假设这意味着给定一个DeptId,您需要使用该DeptId的所有员工的所有属性:

using (var dbContext = new MyDbContext(...))
{
    var myDepartment = dbContext.Departments
        .Where(department => department.DepartmentId == DeptId)
        .SingleOrDefault();
    // I know there is at utmost one, because it is a primary key

    if (myDepartment == null) ShowDepartmentMissing(...);

    var employeesOfDepartment = myDepartment.Employees
        .Select(employee => new
        {
            FirstName = employee.FirstName,
            LastName = employee.LastName,
            Benefits = employee.Benefits,
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM