查询首先加入表c#代码

时间:2018-02-27 21:57:06

标签: c# entity-framework join code-first

我使用代码优先方法在c#中创建了这些表。

员工类:

public int id { get; set; }
public string name { get; set; }

系类:

public int id { get; set; }
public string deptName { get; set; }
public IQueryable<Employee> { get; set; }

这会在我的sql数据库的Employee表中生成一个DepartmentID。但是我无法在c#中访问此字段,因为DepartmentID不是员工类/模型中的字段。

我的问题是如何访问此变量。我希望做一些不同的联接等,但我正在努力解决这个问题。

1 个答案:

答案 0 :(得分:0)

你当然可以expose the foreign key,但不一定需要它。 EF的美妙之处在于你不需要加入。

首先我会清理你的课程:

public class Employee
{
    public int ID { get; set; }
    public string Name { get; set; }

    // Exposed FK. By convention, EF know this is a FK.
    // EF will add one if you omit it.
    public int DepartmentID { get; set; }  
    // Navigation properties are how you access the related (joined) data
    public virtual Department Department { get; set; }  
}

public class Department
{
    public int ID { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Employee> Employees { get; set; }
}

现在您可以轻松查询数据:

var employeeWithDepartment = context.Employee
      .Include(e => e.Department)
      .FirstOrDefault(e => e.ID = 123);

var employeeName = employeeWithDepartment.Name;
var departmentName = employeeWithDepartment.Department.Name;
... etc.

var departmentWithListOfEmployees = context.Departments
     .Include(d => d.Employees)
     .Where(d => d.Name == "Accounting")
     .ToList();

... build table or something
foreach (var employee in departmentWithListOfEmployees.Employees)
{
     <tr><td>@employee.ID</td><td>@employee.Name</td>
}
... close table