Find if an item is duplicated.
Expected: an exception to be thrown only if more than one item is found. but we get a different exception here?
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] An exception occurred while iterating over the results of a query for context type '….ApplicationDbContext'.
System.InvalidOperationException: Source sequence doesn't contain any elements.
at System.Linq.AsyncEnumerable.Single_[TSource](IAsyncEnumerable1 source, CancellationToken cancellationToken) in D:\a\1\s\Ix.NET\Source\System.Interactive.Async\Single.cs:line 136
1.Enumerator.MoveNext(CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.TaskResultAsyncEnumerable
at System.Linq.AsyncEnumerable.SelectEnumerableAsyncIterator2.MoveNextCore(CancellationToken cancellationToken) in D:\a\1\s\Ix.NET\Source\System.Interactive.Async\Select.cs:line 106
1.MoveNext(CancellationToken cancellationToken) in D:\a\1\s\Ix.NET\Source\System.Interactive.Async\AsyncIterator.cs:line 98
at System.Linq.AsyncEnumerable.AsyncIterator
at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.ExceptionInterceptor1.EnumeratorExceptionInterceptor.MoveNext(CancellationToken cancellationToken)
2 compiledQuery, IDiagnosticsLogger`1 logger, Type contextType)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteSingletonAsyncQuery[TResult](QueryContext queryContext, FuncSystem.InvalidOperationException: Source sequence doesn't contain any
elements. at
System.Linq.AsyncEnumerable.Single_[TSource](IAsyncEnumerable1
1.Enumerator.MoveNext(CancellationToken
source, CancellationToken cancellationToken) in
D:\a\1\s\Ix.NET\Source\System.Interactive.Async\Single.cs:line 136
at
Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.TaskResultAsyncEnumerable
cancellationToken) at
System.Linq.AsyncEnumerable.SelectEnumerableAsyncIterator2.MoveNextCore(CancellationToken
1.MoveNext(CancellationToken
cancellationToken) in
D:\a\1\s\Ix.NET\Source\System.Interactive.Async\Select.cs:line 106
at
System.Linq.AsyncEnumerable.AsyncIterator
cancellationToken) in
D:\a\1\s\Ix.NET\Source\System.Interactive.Async\AsyncIterator.cs:line
98 at
Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.ExceptionInterceptor1.EnumeratorExceptionInterceptor.MoveNext(CancellationToken
2 compiledQuery, IDiagnosticsLogger`1 logger, Type
cancellationToken) at
Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteSingletonAsyncQuery[TResult](QueryContext
queryContext, Func
contextType)
Best Answer
You are confusing
SingleAsync
withSingleOrDefaultAsync
.SingleAsync
-> means that it will throw if no entries or more than one entry is foundSingleOrDefaultAsync
-> means that it will throw if two or more entries are found