我正在使用EF5和代码创建一个项目。
在我的对象设计中,我使用了“独立协会”,在这种情况下,属性“FarmWhereCowLives”是“独立协会”。
public class Cow
{
public int CowId
public string Name
public DateTime Birthday
public Farm FarmWhereCowLives
}
public class Farm
{
public int FarmId
public string Name
public string Suburb
}
然而,当我去运行一个查询,要求Entity Framework通过传入农场ID来为特定农场选择最新的牛...例如:
_dbset.AsQueryable().Where(c => c.FarmWhereCowLives.FarmId == 1).OrderByDescending(c => c.Birthday).Take(1).Single()
(我正在使用通用存储库,以防相关,但我不这么认为)
执行的sql(我可以在SQL profiler中看到它)似乎过于复杂了?
例如
SELECT TOP (1)
[Project1].[CowId] AS [CowId],
[Project1].[Name] AS [Name],
[Project1].[Birthday] AS [Birthday],
[Project1].[FarmWhereCowLives_FarmId] AS [FarmWhereCowLives_FarmId]
FROM
(
SELECT
[Extent1].[RateChangeId] AS [RateChangeId],
[Extent1].[CowId] AS [CowId],
[Extent1].[Name] AS [Name],
[Extent1].[Birthday] AS [Birthday],
[Extent1].[FarmWhereCowLives_FarmId] AS [FarmWhereCowLives_FarmId]
FROM [dbo].[Cow] AS [Extent1]
WHERE [Extent1].[FarmWhereCowLives_FarmId] = 1
)
AS [Project1]
ORDER BY [Project1].[Birthday] DESC'
问题是:
也许我在这里做错了什么?
干杯 安德鲁
答案 0 :(得分:0)
EF总是使用嵌套查询 - 我不知何故会期望它也会使用嵌套查询进行FK关联。它并不一定意味着查询不正确。数据库中的查询优化器可以在执行前简化查询。