Home > database >  EF Core 6 – ToQueryString() on a query created with FromSqlRaw thows exception "Sequence contai
EF Core 6 – ToQueryString() on a query created with FromSqlRaw thows exception "Sequence contai

Time:02-18

It is the first time I'm using the query mode of EF Core. Because my large query with parameters threw also the exception "Sequence contains no elements".

System.InvalidOperationException
  HResult=0x80131509
  Message=Sequence contains no elements
  Source=System.Linq
  StackTrace:
   at System.Linq.ThrowHelper.ThrowNoElementsException()
   at System.Linq.Enumerable.Max(IEnumerable`1 source)
   at Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.VisitBinary(BinaryExpression binaryExpression)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at System.Dynamic.Utils.ExpressionVisitorUtils.VisitBlockExpressions(ExpressionVisitor visitor, BlockExpression block)
   at System.Linq.Expressions.ExpressionVisitor.VisitBlock(BlockExpression node)
   at System.Linq.Expressions.BlockExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.VisitExtension(Expression extensionExpression)
   at System.Linq.Expressions.Expression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.ProcessShaper(Expression shaperExpression, RelationalCommandCache& relationalCommandCache, LambdaExpression& relatedDataLoaders, Int32& collectionId)
   at Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor.VisitShapedQuery(ShapedQueryExpression shapedQueryExpression)
   at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.VisitExtension(Expression extensionExpression)
   at System.Linq.Expressions.Expression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   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)
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToQueryString(IQueryable source)
   at Elwis.Orders.Persistence.GroupQueries.GetGroups(AccountId accountId, SalesGroupId salesGroupId, GroupStatus groupStatus, GroupAccountRole groupAccountRole, PermissionLevel permissionLevel, String sortingColumn, SortingDirection sortingDirection, Int32 pageSize, Int32 pageNumber) in C:\Users\micro\source\repos\rtsforder\Elwis.Orders.Persistence\Read\Queries\GroupQueries.cs:line 50

  This exception was originally thrown at this call stack:
    [External Code]
    Elwis.Orders.Persistence.GroupQueries.GetGroups(Elwis.SharedKernel.Domain.AccountId, Elwis.Orders.Domain.SalesGroupId, Elwis.Orders.Domain.GroupStatus, Elwis.Orders.Domain.GroupAccountRole, Elwis.SharedKernel.Domain.PermissionLevel, string, Elwis.SharedKernel.Domain.Enums.SortingDirection, int, int) in GroupQueries.cs

I simplified the sql code to localize the error and returned constant values from joined tables. I used ToQueryString() to output the generated SQL to the console.

var query = _dbContext.Set<GetGroupDTO>().FromSqlRaw(@"
    Select  GroupId, SalesGroupName='RTSF', Name, Owner, Status='OPEN', 
    [Start], [End], AccountRole='Owner', Suspended, 
    Created, LastUpdated, ChangedBy, _eTag
    FROM OD.[Group]");

Console.WriteLine(query.ToQueryString());

ToQueryString() should not run the query, just output the SQL. Since the above test SQL does not use any parameters it should not throw any errors. I don't understand what causes this error?

The query object is created here:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   base.OnModelCreating(modelBuilder);
   modelBuilder.Entity<GetGroupDTO>().HasNoKey();
}

The class to hold the query result:

public class GetGroupDTO
{
    public Guid GroupId { get; }
    public string SalesGroupName { get; }
    public string Name { get; }
    public Guid Owner { get; }
    public string Status { get; }
    public DateTime Start { get; }
    public DateTime End { get; }
    public string AccountRole { get; }
    private bool Suspended { get; }
    public DateTime Created { get; }
    public DateTime LastUpdated { get; }
    public Guid ChangedBy { get; }
    public ulong _eTag { get; }

    private GetGroupDTO() { }
}

Is there any other code needed to answer the question?

Update:

I tried another SQL statement that used the Group object that is used for writing. This time the call went through. It seems the error comes from the declaration of the query object.

var group = _dbContext.Set<Group>()
  .FromSqlRaw("SELECT * FROM OD.[Group]").ToList();

CodePudding user response:

Add set or init for your properties. EF Core cannot generate assignment for readonly properties that's why it fails.

Probably they have to throw more informative exception for such case.

  • Related