我更新了我的项目到dotnet core 3.0RC1(也可能是preview9),但我的原本可用的代码无法正常工作。
var value = context.Products.Where(t => t.CategoryId == catId).Select(t => t.Version).DefaultIfEmpty().Max();
出现了System.InvalidOperationException: Sequence contains no elements
异常。受影响的表为空。
如果我添加ToList()
,使代码如下:DeafultIfEmpty().ToList().Max()
,则代码重新运行正常。没有找到任何关于破坏性更改的信息。 当我运行时
var expectedZero = new List<int>().DefaultIfEmpty().Max();
它能够正常工作。这让我觉得可能是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)
编辑
产品类别:
[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; }
}
第二次编辑 EF Core生成的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
Version
属性? - MichaelM.DefaultIfEmpty()
的结果返回Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable<int>
,其中包含一个类型为int的IEnumerable,其Results View包含1个项目= 0。 - mikeyy