【问题标题】:Query joined tables c# code first先查询连接表c#代码
【发布时间】:2018-02-27 21:57:06
【问题描述】:

我有这些表是我用代码优先的方法在 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 不是员工类/模型中的字段。

我的问题是如何访问这个变量。我希望做一些不同的连接等,但我正在为此苦苦挣扎。

【问题讨论】:

  • 为什么不在模型中添加那一列?
  • 我有点想,既然这些列可以自动生成,我会利用它。这是唯一的解决方案吗?
  • 当您想使用 EF 时,这是正确的方法。没有声明导航属性就没有关系。

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


【解决方案1】:

您当然可以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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-09
    • 1970-01-01
    相关资源
    最近更新 更多