简体   繁体   English

无法在方法中执行 efcore 子查询(以提高可读性)

[英]Can't do efcore subquery in method (to improve readability)

I am trying to make my code a little bit cleaner and easier to read but I am getting an efcore exception (they indicate this might be a limitation), just wanted to see if anyone can help.我试图让我的代码更简洁、更易于阅读,但我遇到了一个 efcore 异常(他们表示这可能是一个限制),只是想看看是否有人可以提供帮助。

I am using .net3.1 and efcore also 3.1.我使用的是 .net3.1,efcore 也是 3.1。

Original code working:原始代码工作:

    public Response GetAll(long myId, DataSourceLoadOptions loadOptions)
    {
        var dbContext = ContextFactory.GetContext<IMyContext>();
        var query = dbContext.Table1.Where(_ => _.Id == myId).Select(ent1 => new
        {
            Id = ent1.Id,
            State = ent1.State,
            MatCode = ent1.Mat.Code,
            AmountToFulfill = ent1.AmountRequested,
            AmountReserved = dbContext.Table2.Where(matres => matres.Ent1Id == ent1.Id && matres.State == MaterialReservationState.Active).Select(_ => _.AmountReserved).Sum(),
            LastChangeTime = ent1.ChangeTime,
        });

        return query.ToList();
    }

Not working code:不工作的代码:

    public Response GetAll2(long myId, DataSourceLoadOptions loadOptions)
    {
        var dbContext = ContextFactory.GetContext<IMyContext>();
        var query = dbContext.Table1.Where(_ => _.Id == myId).Select(ent1 => new
        {
            Id = ent1.Id,
            State = ent1.State,
            MatCode = ent1.Mat.Code,
            AmountToFulfill = ent1.AmountRequested,
            AmountReserved = GetReservedAmount(dbContext, ent1).Sum(),
            LastChangeTime = ent1.ChangeTime,
        });

        return query.ToList();
    }

    private static IQueryable<int> GetReservedAmount(IMyContext dbContext, IEntity1 ent1)
    {
        return dbContext.Table2
            .Where(matres => matres.Ent1Id == ent1.Id && matres.State == MaterialReservationState.Active)
            .Select(_ => _.AmountReserved);
    }

Exception:例外:

[21:26:28.1605 ERR] An unhandled exception has occurred while executing the request. [21:26:28.1605 ERR] 执行请求时发生未处理的异常。 {EventId={Id=1, Name="UnhandledException"}, SourceContext="Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware", RequestId="0HxxxxxA83M7JB:00000001", RequestPath="/xxxxxxxxxx/2", SpanId="|5exxx39-48248xxxxx5b806.1.eee74277_", TraceId="5e3cde39-4824xxxxx", ParentId="|5e3cxxde39-48248xxxxxa25b806.1.", ConnectionId="0xxxxxx", ThreadId=11} System.InvalidOperationException: Processing of the LINQ expression 'ClassName.GetAll2( dbContext: __dbContext_1, op: (NavigationTreeExpression Value: (EntityReference: Entity1) Expression: o.Outer)).Sum()' by 'NavigationExpandingExpressionVisitor' failed. {EventId={Id=1, Name="UnhandledException"}, SourceContext="Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware", RequestId="0HxxxxxA83M7JB:00000001", RequestPath="/xxxxxxxxxx/2", SpanId="|5exxx39- 48248xxxxx5b806.1.eee74277_", TraceId="5e3cde39-4824xxxxx", ParentId="|5e3cxxde39-48248xxxxxa25b806.1", ConnectionId="0xxxxxx", ThreadId=11} System.InvalidOperationException: 处理 884250Get63558382 表达式 'ClassNameAll ( dbContext: __dbContext_1, op: (NavigationTreeExpression Value: (EntityReference: Entity1) Expression: o.Outer)).Sum()' by 'NavigationExpandingExpressionVisitor' 失败。 This may indicate either a bug or a limitation in EF Core.这可能表示 EF Core 中存在错误或限制。 See https://go.microsoft.com/fwlink/?linkid=2101433 for more detailed information.有关详细信息,请参阅https://go.microsoft.com/fwlink/?linkid=2101433 at Microsoft.EntityFrameworkCore.Query.Internal.NavigationExpandingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression).......在 Microsoft.EntityFrameworkCore.Query.Internal.NavigationExpandingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)......

The error you've got give you complete explanation what's wrong there:你得到的错误给你完整的解释那里出了什么问题:

Processing of the LINQ expression 'ClassName.GetAll2( dbContext: __dbContext_1, op: (NavigationTreeExpression Value: (EntityReference: Entity1) Expression: o.Outer)).Sum()' by 'NavigationExpandingExpressionVisitor' failed. 'NavigationExpandingExpressionVisitor' 处理 LINQ 表达式 'ClassName.GetAll2( dbContext: __dbContext_1, op: (NavigationTreeExpression Value: (EntityReference: Entity1) Expression: o.Outer)).Sum()' 失败。

If you go to provided link ( https://go.microsoft.com/fwlink/?linkid=2101433 ) then you can read that:如果您 go 提供链接 ( https://go.microsoft.com/fwlink/?linkid=2101433 ) 那么您可以阅读:

EF Core supports partial client evaluation in the top-level projection (essentially, the last call to Select()). EF Core 支持顶级投影中的部分客户端评估(本质上是对 Select() 的最后一次调用)。 If the top-level projection in the query can't be translated to the server, EF Core will fetch any required data from the server and evaluate remaining parts of the query on the client.如果查询中的顶级投影无法转换为服务器,EF Core 将从服务器获取任何所需数据并在客户端评估查询的其余部分。 If EF Core detects an expression, in any place other than the top-level projection, which can't be translated to the server, then it throws a runtime exception.如果 EF Core 在顶级投影以外的任何地方检测到无法转换为服务器的表达式,则会引发运行时异常。

Your method你的方法

private static IQueryable<int> GetReservedAmount(IMyContext dbContext, IEntity1 ent1)
{
    return dbContext.Table2
        .Where(matres => matres.Ent1Id == ent1.Id && matres.State == MaterialReservationState.Active)
        .Select(_ => _.AmountReserved);
}

can't be translated to TSQL query syntax.无法转换为 TSQL 查询语法。

That's it, from EF Core version 3.0 client methods can't be translated to TSQL.就是这样,从 EF Core 版本 3.0 开始,客户端方法无法转换为 TSQL。

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

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