當使用實體框架(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()可能會返回整個數據庫非常有幫助!