我有一個非常簡單的(代碼優先)模式:實體框架 - 不當的2條select語句代替連接
員工
[Table("vEmployee")] //note v - it's a view
public class Employee
{
[Key]
public int EmployeeNumber { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
EmployeeHolidayEntitlement
[Table("tblEmployeeHolidayEntitlement")]
public class EmployeeHolidayEntitlement
{
[Key]
public int EmployeeNumber { get; set; }
public virtual Employee Employee { get; set; }
public decimal StandardEntitlement { get; set; }
//.....omitted for brevity
}
請注意,EmployeeHolidayEntitlement映射到at能和員工被映射到一個視圖
當建立我的背景,我做的:
(不知道這是正確的!)
modelBuilder.Entity<Employee>()
.HasOptional(x => x.HolidayEntitlement)
.WithRequired(x => x.Employee);
現在,當我查詢,像這樣:
var db = new ApiContext();
var result = db.Employees.ToList();
這很慢。
如果我期待在SQL事件探查器,我可以看到,而不是一個聲明(加盟vEmployee和tblEmployeeHolidayEntitlement)我得到很多的語句執行(每員工記錄之一) - 例如:
首先,它從選擇vEmployee
SELECT
[Extent1].[id] AS [EmployeeNumber],
[Extent1].[FirstName] AS [FirstName],
[Extent1].[LastName] AS [LastName],
FROM [dbo].[vEmployee] AS [Extent1]
那麼這些爲每個記錄一個返回
exec sp_executesql N'SELECT
[Extent1].[EmployeeNumber] AS [EmployeeNumber],
[Extent1].[StandardEntitlement] AS [StandardEntitlement]
FROM [dbo].[tblEmployeeHolidayEntitlement] AS [Extent1]
WHERE [Extent1].[EmployeeNumber] = @EntityKeyValue1',N'@EntityKeyValue1 int',@EntityKeyValue1=175219
這似乎不是我的權利 -
我會想到它應該沿左線做一些更多的JOIN像
SELECT *
FROM [dbo].[vEmployee] employee
LEFT JOIN
[dbo].[tblEmployeeHolidayEntitlement employeeEntitlement
ON
employee.id = employeeEntitlement.employeenumber
關於.Include,我不能指定一個lambda,它想要一個字符串? – Alex 2014-10-16 19:24:09
@Alex您需要使用'using'語句來訪問'.Include'的lambda超載,請參閱:http://stackoverflow.com/a/10079815/84206 – AaronLS 2014-10-16 19:25:14
您使用的是EF6嗎? lambda重載更新,但字符串重載做同樣的事情...看到這裏:http://msdn.microsoft.com/en-us/library/system.data.entity.dbextensions.include(v=vs。 103).aspx – Casey 2014-10-16 19:25:28