简体   繁体   English

EF Core 6 – ToQueryString() 在使用 FromSqlRaw 创建的查询上抛出异常“序列不包含任何元素”

[英]EF Core 6 – ToQueryString() on a query created with FromSqlRaw thows exception "Sequence contains no elements"

It is the first time I'm using the query mode of EF Core.这是我第一次使用 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.我简化了 sql 代码以定位错误并从连接表返回常量值。 I used ToQueryString() to output the generated SQL to the console.我使用ToQueryString()到 output 生成的 SQL 到控制台。

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. ToQueryString()不应该运行查询,只是 output 和 SQL。由于上面的测试 SQL 不使用任何参数,它不应该抛出任何错误。 I don't understand what causes this error?我不明白是什么导致了这个错误?

The query object is created here:查询 object 是在此处创建的:

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

The class to hold the query result: class 存放查询结果:

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.我尝试了另一个 SQL 语句,该语句使用了用于写入的组 object。 This time the call went through.这次电话接通了。 It seems the error comes from the declaration of the query object.错误似乎来自查询 object 的声明。

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

Add set or init for your properties.为您的属性添加setinit EF Core cannot generate assignment for readonly properties that's why it fails. EF Core 无法为只读属性生成分配,这就是它失败的原因。

Probably they have to throw more informative exception for such case.对于这种情况,他们可能必须抛出更多信息异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM