使用实体框架 (EF) 时,最佳解决方案是使用 LINQ (http://msdn.microsoft.com/en-us/library/bb308959.aspx) 查询 EF 上下文。 LINQ 可用于跨关系查询,因此在您的场景中,您的代码如下所示:
var joinedlist = context.Student.Join(
// The table we wish to join to the Student table
context.Department,
// Item on student table we want to join from
studentItem => studentItem.DeptId,
// Item on department table we want to join to
departmentItem => departmentItem.Deptd,
// New object just holding the values we wish to retrieve from the joined tables
(studentItem, departmentItem) => new {
StudentId = studentItem.StudentId,
StudentUsername = studentItem.Username,
StudentAddress = studentItem.Address,
DepartmentName = departmentItem.DeptName,
Navigation = StudentItem.NavigationProp1Id
}
);
上面的代码将为您生成一个可查询的列表,但您可以使用 LINQ 做更多的事情。例如选择数据子集并过滤结果:
var singleItem = joinedlist
// Filter our joined list
.Where(item => item.StudentId.Equals(1))
// Select only a subset of columns
.Select(item => new {item.StudentUsername, item.StudentAddress})
// Return only a single item
.FirstOrDefault();
关于性能 - 我建议获取一个分析器,它可以向您显示 EF 上的 LINQ 语句的 SQL 输出。这真的有助于理解延迟加载以及放错位置的 .ToList() 可能会返回整个数据库的位置!