实体框架Core GroupJoin& GroupBy生成意外的SQL

时间:2017-05-20 04:30:06

标签: entity-framework-core linqpad

我正在尝试查询5条父记录,然后查询所有子类别和计数的摘要:

 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的预期效果一致---我得到前5个父记录的一个查询,然后是总结每个子组的五个查询。

然而,在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]

我没想到第一个查询中的左连接,它给了我所有的子记录。

这是我的查询问题吗?

1 个答案:

答案 0 :(得分: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 Core错误:

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