【发布时间】:2019-11-03 12:19:36
【问题描述】:
查找项目是否重复。 预期:仅在找到多个项目时才抛出异常。但我们在这里得到一个不同的例外?
try
{
// Find duplicate item
duplicateItem = await _context.Items
.SingleAsync(m => m.UserId == userId && m.Name == "some item");
}
catch (Exception)
{
//Exception more than one item found
}
[01:48:06 ERR] 迭代上下文类型“....ApplicationDbContext”的查询结果时发生异常。 System.InvalidOperationException:源序列不包含任何元素。 在 System.Linq.AsyncEnumerable.Single_[TSource](IAsyncEnumerable
1 source, CancellationToken cancellationToken) in D:\a\1\s\Ix.NET\Source\System.Interactive.Async\Single.cs:line 136 at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.TaskResultAsyncEnumerable1.Enumerator.MoveNext(CancellationToken cancelToken) 在 D:\a\1\s\Ix.NET\Source\System.Interactive.Async\AsyncIterator.cs:line 98 中的 System.Linq.AsyncEnumerable.SelectEnumerableAsyncIterator2.MoveNextCore(CancellationToken cancellationToken) in D:\a\1\s\Ix.NET\Source\System.Interactive.Async\Select.cs:line 106 at System.Linq.AsyncEnumerable.AsyncIterator1.MoveNext(CancellationToken cancelToken) 在 Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.ExceptionInterceptor1.EnumeratorExceptionInterceptor.MoveNext(CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteSingletonAsyncQuery[TResult](QueryContext queryContext, Func2 编译查询,IDiagnosticsLogger`1 记录器,类型 contextType)System.InvalidOperationException:源序列不包含任何 元素。在 System.Linq.AsyncEnumerable.Single_[TSource](IAsyncEnumerable
1 source, CancellationToken cancellationToken) in D:\a\1\s\Ix.NET\Source\System.Interactive.Async\Single.cs:line 1361.Enumerator.MoveNext(CancellationToken 取消令牌)在 System.Linq.AsyncEnumerable.SelectEnumerableAsyncIterator
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.TaskResultAsyncEnumerable2.MoveNextCore(CancellationToken cancellationToken) in D:\a\1\s\Ix.NET\Source\System.Interactive.Async\Select.cs:line 1061.MoveNext(CancellationToken 取消令牌)在 D:\a\1\s\Ix.NET\Source\System.Interactive.Async\AsyncIterator.cs:line 98 在 Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.ExceptionInterceptor
at System.Linq.AsyncEnumerable.AsyncIterator1.EnumeratorExceptionInterceptor.MoveNext(CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteSingletonAsyncQuery[TResult](QueryContext queryContext, Func2 编译查询,IDiagnosticsLogger`1 记录器,类型 上下文类型)
【问题讨论】:
-
如果有零个或多个项目,
Single[Async]会抛出,我在这里没有得到你的问题。 -
旁注:如果您想检查集合是否有重复项,则可以毫无例外地完成。只需
.Where(<your condition>).Take(2).ToList(),然后只需检查该列表的长度 -
@AleksAndreev 有趣的是,在实体框架中调用
Single无论如何都会执行Take(2)... -
请改用
SingleOrDefaultAsync,Single期望只有一个实体与您给它的条件相匹配(正好是一个),而SingleOrDefault期望最多一个匹配的实体(零或一)。
标签: c# entity-framework linq asp.net-core