question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Max with 0 result give error Sequence contains no elements when using .Max() or .MaxAsync()

See original GitHub issue

When the result of max is 0 a error message is generated

Steps to reproduce

_ctx.ChapterQuestions.Where(x => x.SurveyChapterId == surveyChapterId).Max(x => x.SequenceNumber+0) // produce error

_ctx.ChapterQuestions.Where(x => x.SurveyChapterId == surveyChapterId).Max(x => x.SequenceNumber+1) // is allowed

sql data

SELECT id,SequenceNumber FROM [ChapterQuestions] AS [c] WHERE [c].[SurveyChapterId] = 702
---
Id	SequenceNumber	
2293	0	

stack trace

dbug: Microsoft.EntityFrameworkCore.Query[10107]
      (queryContext) => Single<int>(new QueryingEnumerable<int>(
          (RelationalQueryContext)queryContext,
          SqlServerQuerySqlGeneratorFactory,
          SqlExpressionFactory,
          ParameterNameGeneratorFactory,
          Projection Mapping:
              EmptyProjectionMember -> 0
          SELECT MAX(c.SequenceNumber + 0)
          FROM ChapterQuestions AS c
          WHERE (c.SurveyChapterId == @__surveyChapterId_0) && NotEqual(@__surveyChapterId_0),
          Func<QueryContext, DbDataReader, ResultContext, int[], ResultCoordinator, int>,
          Survey.Entities.Context.SurveyContext,
          DiagnosticsLogger<Query>
      ))
dbug: Microsoft.EntityFrameworkCore.Database.Command[20103]
      Creating DbCommand for 'ExecuteReader'.
dbug: Microsoft.EntityFrameworkCore.Database.Command[20104]
      Created DbCommand for 'ExecuteReader' (0ms).
dbug: Microsoft.EntityFrameworkCore.Database.Connection[20000]
      Opening connection to database 'survey' on server '(localdb)\mssqllocaldb'.
dbug: Microsoft.EntityFrameworkCore.Database.Connection[20001]
      Opened connection to database 'survey' on server '(localdb)\mssqllocaldb'.
info: Microsoft.EntityFrameworkCore.Database.Command[20100]
      Executing DbCommand [Parameters=[@__surveyChapterId_0='702'], CommandType='Text', CommandTimeout='30']
      SELECT MAX([c].[SequenceNumber] + 0)
      FROM [ChapterQuestions] AS [c]
      WHERE ([c].[SurveyChapterId] = @__surveyChapterId_0) AND @__surveyChapterId_0 IS NOT NULL
dbug: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (3ms) [Parameters=[@__surveyChapterId_0='702'], CommandType='Text', CommandTimeout='30']
      SELECT MAX([c].[SequenceNumber] + 0)
      FROM [ChapterQuestions] AS [c]
      WHERE ([c].[SurveyChapterId] = @__surveyChapterId_0) AND @__surveyChapterId_0 IS NOT NULL
fail: Microsoft.EntityFrameworkCore.Query[10100]
      An exception occurred while iterating over the results of a query for context type 'Survey.Entities.Context.SurveyContext'.
      System.InvalidOperationException: Sequence contains no elements.
         at lambda_method(Closure , QueryContext , DbDataReader , ResultContext , Int32[] , ResultCoordinator )
         at Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor.QueryingEnumerable`1.Enumerator.MoveNext()
System.InvalidOperationException: Sequence contains no elements.
   at lambda_method(Closure , QueryContext , DbDataReader , ResultContext , Int32[] , ResultCoordinator )
   at Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor.QueryingEnumerable`1.Enumerator.MoveNext()
dbug: Microsoft.EntityFrameworkCore.Database.Command[20300]
      A data reader was disposed.
dbug: Microsoft.EntityFrameworkCore.Database.Connection[20002]
      Closing connection to database 'survey' on server '(localdb)\mssqllocaldb'.
dbug: Microsoft.EntityFrameworkCore.Database.Connection[20003]
      Closed connection to database 'survey' on server '(localdb)\mssqllocaldb'.
info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[2]
      Executed action Survey.WebApi.Survey.ManageSurveys.Controllers.SurveyManagementController.InsertChapterQuestion (Survey.WebApi) in 39.4262ms
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[1]
      Executed endpoint 'Survey.WebApi.Survey.ManageSurveys.Controllers.SurveyManagementController.InsertChapterQuestion (Survey.WebApi)'
fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[1]
      An unhandled exception has occurred while executing the request.
System.InvalidOperationException: Sequence contains no elements.
   at lambda_method(Closure , QueryContext , DbDataReader , ResultContext , Int32[] , ResultCoordinator )
   at Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor.QueryingEnumerable`1.Enumerator.MoveNext()
   at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
   at System.Linq.Queryable.Max[TSource,TResult](IQueryable`1 source, Expression`1 selector)
   at Survey.WebApi.Survey.ManageSurveys.DbServices.ManageSurveyQuestionProvider.InsertChapterQuestion(Int32 surveyId, Int32 surveyChapterId, Int32 questionId) in C:\git\mijnzorgpeiler\Survey\Survey.WebApi\Survey\ManageSurveys\DbServices\ManageSurveyQuestionProvider.cs:line 50
   at Survey.WebApi.Survey.ManageSurveys.Services.ManageSurveyService.InsertChapterQuestion(Int32 surveyId, Int32 surveyChapterId, Int32 questionId) in C:\git\mijnzorgpeiler\Survey\Survey.WebApi\Survey\ManageSurveys\Services\ManageSurveyService.cs:line 69
   at Survey.WebApi.Survey.ManageSurveys.Controllers.SurveyManagementController.InsertChapterQuestion(Int32 surveyId, Int32 surveyChapterId, Int32 questionId) in C:\git\mijnzorgpeiler\Survey\Survey.WebApi\Survey\ManageSurveys\Controllers\SurveyManagementController.cs:line 59
   at lambda_method(Closure , Object )
   at Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable.Awaiter.GetResult()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()

Further technical details

EF Core version: Database provider: (e.g. Microsoft.EntityFrameworkCore.SqlServer) Target framework: (e.g. .NET Core 3.1) Operating system: IDE: (e.g. Visual Studio 2019 16.4)

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:2
  • Comments:8 (2 by maintainers)

github_iconTop GitHub Comments

2reactions
myesncommented, Dec 31, 2019

May I ask when version 3.1.1 can be released, I also encountered the same problem.

I found the weekly status updates link

1reaction
rojicommented, Jan 26, 2022

@Pyrdacor we have various cases where we don’t match the .NET behavior - a good example is string equality, which on some databases is case-insensitive whereas it’s case-sensitive in .NET. The team was unanimous that there’s more danger in mimicking the (problematic) .NET behavior (data corruption) than there is in the current behavior.

As to this being understandable or not, that’s quite subjective - it seems pretty clear to me that Max is saying it has no values. In any case, better an exception that the user can investigate in understand, than silent bad data because of an implicit conversion from null string to zero.

Read more comments on GitHub >

github_iconTop Results From Across the Web

c# - Ef core: Sequence contains no element when doing ...
MaxAsync (x => x. OrderIndex); The problem is when the example db set is containing 0 elements. This will throw an exception: Sequence...
Read more >
Sequence contains no element when doing MaxAsync-Entity ...
You can use DefaultIfEmpty and Select before MaxAsync. ... Here you won't have to retrieve all of the items from the database, only...
Read more >
How to fix max() error "sequence contains no elements"
Solution 1. The problem is pretty clear - families is an empty collection. Since it has no elements, it has no maximum or...
Read more >
Sequence contains no elements, ERROR - Microsoft Q&A
Probably the data are incomplete or invalid, because this error means that Single cannot find any row. To skip this step, try something...
Read more >
Siebel Performance Tuning Guide
The number of application users actively using and accessing the Siebel application, or a particular element, such as a Siebel Application Object Manager....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found