【问题标题】:Merge two Entity Framework queries into one将两个实体框架查询合并为一个
【发布时间】:2022-07-21 23:15:44
【问题描述】:

我在一种方法中有两个查询。它们之间的区别在于,当方法中传递的organizationId 不为空时,您应该通过organizationId 查找。当方法中organizationId为null时,则通过phoneNumberorganizationId为null检索所有操作。请参阅以下内容:

public async Task<decimal> CalculateDifferenceBetweenEntriesAndConsummations(string? phoneNumber,
    int? organizationId)
{
    if (organizationId != null)
    {
        return await _dbContext.signumid_credit_operation
                               .Where(x => x.OrganizationId == organizationId && 
                                           (x.OperationType == OperationType.Purchase || x.OperationType == OperationType.Refund))
                               .SumAsync(x => x.Amount)
               - await _dbContext.signumid_credit_operation
                                 .Where(x => x.OrganizationId == organizationId && x.OperationType == OperationType.Consummation)
                                 .SumAsync(x => x.Amount);
    }

    return await _dbContext.signumid_credit_operation
                           .Where(x => x.PhoneNumber == phoneNumber && (x.OperationType == OperationType.Purchase || x.OperationType == OperationType.Refund) && x.OrganizationId == null)
                           .SumAsync(x => x.Amount)
           - await _dbContext.signumid_credit_operation
                             .Where(x => x.PhoneNumber == phoneNumber && x.OperationType == OperationType.Consummation && x.OrganizationId == null)
                             .SumAsync(x => x.Amount);
}

我希望在此方法中只有一个 return 组合查询并仍然执行相同的工作。

这可能吗?

【问题讨论】:

  • 你不能只使用第一个查询就完成了吗?如果organizationIdnull,那么第一个查询无论如何都会成为第二个查询。我不完全确定 EF 以这种方式处理可空值类型,但我希望它会。哦,我刚刚意识到phoneNumber 没有在第一个查询中使用。
  • 顺便说一句,这个问题与 ASP.NET 完全没有关系。当代码是在任何应用程序中完全相同的服务方法时,在 ASP.NET 应用程序中使用代码这一事实是无关紧要的。请仅应用与特定问题直接相关的标签。
  • @user18387401,没有,因为第二个查询中有phoneNumber。
  • 我在你回复之前就意识到了,但我太慢了。
  • @user18387401 我同意标签

标签: c# entity-framework


【解决方案1】:

我认为这应该可行:

.Where(x => ((organizationId != null &&
              x.OrganizationId == organizationId) ||
             (organizationId == null &&
              x.OrganizationId == null &&
              x.PhoneNumber == phoneNumber)) &&

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多