首先查询联接表 c# 代码
Query joined tables c# code first
我有这些 table我使用代码优先方法在 c# 中制作的。
员工class:
public int id { get; set; }
public string name { get; set; }
部门class:
public int id { get; set; }
public string deptName { get; set; }
public IQueryable<Employee> { get; set; }
这会在我的 sql 数据库中的我的员工 table 中生成一个 DepartmentID。但是我无法在 c# 中访问此字段,因为 DepartmentID 不是员工 class/model.
中的字段
我的问题是如何访问这个变量。我想做一些不同的连接等,但正在努力解决这个问题。
当然可以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
我有这些 table我使用代码优先方法在 c# 中制作的。
员工class:
public int id { get; set; }
public string name { get; set; }
部门class:
public int id { get; set; }
public string deptName { get; set; }
public IQueryable<Employee> { get; set; }
这会在我的 sql 数据库中的我的员工 table 中生成一个 DepartmentID。但是我无法在 c# 中访问此字段,因为 DepartmentID 不是员工 class/model.
中的字段我的问题是如何访问这个变量。我想做一些不同的连接等,但正在努力解决这个问题。
当然可以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