Search code examples
c#asp.net-coreentity-framework-core.net-8.0

System.InvalidOperationException "Sequence contains no elements" yet using FirstOrDefault


In the code below, both DataSourceM and DataDeliveryM are plain classes (no virtual methods) with all public properties with default values and decorated with [NotMapped].

using (ApplicationDbContext context = new())
{
    foreach (ConfigurationSimple config in result)
    {
         //Query1
         DataSourceM sdResult = context.Database.SqlQueryRaw<DataSourceM>(
             @"SELECT Id, BucketName, Root FROM DataSource where Id = @p0", config.DataSourceId).FirstOrDefault();

         //Query2
         DataDeliveryM ddlResult = context.Database.SqlQueryRaw<DataDeliveryM>(
             @"SELECT DataDeliveryTypeId, FromDirectAddress, ToDirectAddress, BucketName, Folder
             FROM DataDelivery
             WHERE Id = @p0 AND vendorID = @p1", config.DataDeliveryId, config.VendorId).FirstOrDefault();

Query1 succeeds. Query2 fails on .FirstOrDefault() with

System.InvalidOperationException
  HResult=0x80131509
  Message=Sequence contains no elements
  Source=System.Linq
  StackTrace:
   at System.Linq.ThrowHelper.ThrowNoElementsException()
   at System.Linq.Enumerable.MinMaxInteger[T,TMinMax](IEnumerable`1 source)
   at Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.VisitBinary(BinaryExpression binaryExpression)
   at System.Dynamic.Utils.ExpressionVisitorUtils.VisitBlockExpressions(ExpressionVisitor visitor, BlockExpression block)
   at System.Linq.Expressions.ExpressionVisitor.VisitBlock(BlockExpression node)
   at Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.VisitExtension(Expression extensionExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.ProcessShaper(Expression shaperExpression, RelationalCommandCache& relationalCommandCache, IReadOnlyList`1& readerColumns, LambdaExpression& relatedDataLoaders, Int32& collectionId)
   at Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor.VisitShapedQuery(ShapedQueryExpression shapedQueryExpression)
   at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.VisitExtension(Expression extensionExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor.VisitExtension(Expression extensionExpression)
   at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Storage.Database.CompileQuery[TResult](Expression query, Boolean async)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass9_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)

I'm using .Net 8 and Entity Framework Core 8.0.8.

Running the query through MySQL Workbench succeeds and returns 0-many records, depending on the parameters. The exception occurs regardless of the parameter values.

Also, I previously encountered the same exception with Query 1, but after renaming the result class from DataSourceModel to DataSourceM, the exception went away. I tried the same approach with Query 2 without success.

Update

Fixed the call stack, and found the fix. In hindsight, it seems obvious since the NotMapped attribute "Denotes that a property or class should be excluded from database mapping", but I had been thinking it meant "it's ok if this property isn't in the result set."


Solution

  • Ensure at least one property is mapped (i.e. not decorated as NotMapped).

    The class below will cause the exception because the NotMapped attribute "Denotes that a property or class should be excluded from database mapping", which here means no instances can be instantiated because there are no properties that can be mapped to the query.

    public class Foo
    {
        [NotMapped]
        public int Id { get; set; }
    
        [NotMapped]
        public int VendorID { get; set; };
    }