DefaultIfEmpty().Max() 仍然抛出“序列不包含元素”。

mik*_*eyy 9 c# .net-core ef-core-3.0

在我将我的项目更新到 dotnet core 3.0RC1(也可能在 preview9 中)之后,我的代码曾经可以工作

var value = context.Products.Where(t => t.CategoryId == catId).Select(t => t.Version).DefaultIfEmpty().Max();
Run Code Online (Sandbox Code Playgroud)

开始投掷 System.InvalidOperationException: Sequence contains no elements。有问题的表是空的。

如果我添加ToList()它看起来像这样DeafultIfEmpty().ToList().Max(),它会再次开始工作。找不到有关重大更改的任何信息。当我跑

var expectedZero = new List<int>().DefaultIfEmpty().Max();
Run Code Online (Sandbox Code Playgroud)

它工作正常。这让我觉得 EF Core 可能有问题。然后我在 xUnit 中使用完全相同的设置创建了测试,但测试正在通过(表也是空的,使用 InMemoryDatabase 而不是实时 SQL Server 实例)。

我真的很困惑。相关堆栈跟踪:

System.InvalidOperationException: Sequence contains no elements.
   at int lambda_method(Closure, QueryContext, DbDataReader, ResultContext, int[], ResultCoordinator)
   at bool Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor+QueryingEnumerable<T>+Enumerator.MoveNext()
   at TSource System.Linq.Enumerable.Single<TSource>(IEnumerable<TSource> source)
   at TResult Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute<TResult>(Expression query)
   at TResult Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute<TResult>(Expression expression)
   at TSource System.Linq.Queryable.Max<TSource>(IQueryable<TSource> source)
   at ... (my method that run the code)
Run Code Online (Sandbox Code Playgroud)

编辑

产品类别:

   [Table("tmpExtProduct", Schema = "ext")]
    public partial class Product
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int Version { get; set; }

        [Column(TypeName = "datetime")]
        public DateTime ImportDate { get; set; }

        public int CategoryId { get; set; }
        public string Description { get; set; }

        [ForeignKey(nameof(Ext.Category))]
        public int CategoryId { get; set; }        

        [InverseProperty(nameof(Ext.Category.Products))]
        public virtual Category Category { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

由 ef 核心生成的第二次编辑Sql

exec sp_executesql N'SELECT MAX([t0].[Version])
FROM (
    SELECT NULL AS [empty]
) AS [empty]
LEFT JOIN (
    SELECT [p].[Version], [p].[CategoryId], [p].[ImportDate], [p].[Description]
    FROM [ext].[tmpExtProduct] AS [p]
    WHERE (([p].[CategoryId] = @__categoryId_0) AND @__categoryId_0 IS NOT NULL)
) AS [t0] ON 1 = 1',N'@__categoryId_0 int',@__categoryId_0=5
Run Code Online (Sandbox Code Playgroud)

mik*_*eyy 6

所以我在 EF Core 存储库中打开了这个问题并得到了答案。显然这是当前的行为,以后可能会改变。

建议使用以下方法

var valueFail = context.Products.Where(t => t.CategoryId == catId)
                .GroupBy(e => 1)
                .Select(t => t.Max(e => e.Version))
                .ToList()[0];
Run Code Online (Sandbox Code Playgroud)

这比我的解决方法更好,DeafultIfEmpty().ToList().Max()因为它将在服务器端完成所有工作,而我的解决方案将在客户端计算 Max() 。