【问题标题】:Entity Framework Core GroupJoin & GroupBy produces unexpected SQLEntity Framework Core GroupJoin & GroupBy 产生意外的 SQL
【发布时间】:2017-05-20 04:30:05
【问题描述】:

我正在尝试查询 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]

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

这是我的查询有问题吗?

【问题讨论】:

    标签: entity-framework-core linqpad


    【解决方案1】:

    部分想通了。子类同时具有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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-30
      • 2022-09-22
      • 1970-01-01
      • 2016-12-16
      • 2018-07-04
      • 1970-01-01
      相关资源
      最近更新 更多