2017-05-20 68 views
0

我試圖查詢5條父記錄,那麼所有的子類別和計數的總結:實體框架的核心羣組加入&的GroupBy產生意外SQL

context.Parent 
     .Take(5) 
     .GroupJoin(inner: context.Child, 
       outerKeySelector: parent => parent.Id, 
       innerKeySelector: child => child.ParentId, 
       resultSelector: (parent, children) => new SummaryResult 
       { 
        Id = parent.Id, 
        Name = parent.Name, 
        Children = parent.Children 
         .GroupBy(c => c.Category) 
         .Select(group => new ChildCategorySummary 
         { 
         Category = group.Key, 
         Count = group.Count() 
         }) 
        }); 

這個工程從LinkPad預期---我得到一個查詢前五個父記錄,然後五個查詢概括每個子組。

然而,在EF7,我得到這個查詢:

exec sp_executesql N'SELECT [child].[Id], [child].[Category], [t].[Id] 
FROM (
    SELECT TOP(@__p_0) [s0].* 
    FROM [Parent] AS [s0] 
) AS [t] 
LEFT JOIN [Child] AS [child] ON [t].[Id] = [child].[ParentId] 
ORDER BY [t].[Id]',N'@__p_0 int',@__p_0=5 

,然後這個,五次:

SELECT [p].[Id], [p].[Category] 
FROM [Child] AS [p] 

我沒想到左連接在第一個查詢,這給我所有的孩子記錄。

這是我的查詢問題嗎?

回答

0

部分解釋了這一點。子類有兩個ParentParentId

public class Child 
{ 
    [Key] 
    public virtual Guid Id { get; set; } 

    [Required] 
    public virtual Parent Parent { get; set; } 

    public virtual Guid ParentId { get; set; } 

} 

所以selector應該使用必填字段Parent,而不是「ParentId`:

outerKeySelector: parent => parent, 
innerKeySelector: child => child.parent 

不過,我現在有一個不同的錯誤,這似乎是一個EF核心錯誤:

System.ArgumentException : Property 'MyApp.Models.Parent Parent' is not defined for type 'MyApp.Models.Parent' 
Parameter name: property 
    at System.Linq.Expressions.Expression.Property(Expression expression, PropertyInfo property) 
    at System.Linq.Expressions.Expression.MakeMemberAccess(Expression expression, MemberInfo member) 
    ... 

我認爲這是fixed in a prerelease version of EF Core 2