C# - 原始查询执行

问题描述 投票:0回答:1

当我在表上应用计数查询时,查询执行会抛出一个错误,例如缺少必需的字段,因为我只需要获取总计数

处理请求时出错:

“FromSql”操作的结果中不存在所需的列“WorkflowRunId”。在 Microsoft.EntityFrameworkCore.Query.Internal.BufferedDataReader.BufferedDataRecord.InitializeFields()

var countQuery = @"SELECT COUNT(*) AS TotalCount FROM [WorkFlow]";
var totalCount = await _dbContext.Workflow.FromSqlRaw(countQuery, parameters.ToArray()).CountAsync();

我的工作流程模型是,

public class Workflow
{
    [Key]
    // public int Id { get; set; }
    public string? WorkflowRunId { get; set; }
    public string? WorkflowId { get; set; }
    // public string? WorkflowObject { get; set; }
    // public int? ClientId { get; set; }
    public string? Status { get; set; }
    // public string WebhookEvent { get; set; }
    // public string? TaskId { get; set; }
    public string? Payload { get; set; }

    public string? ClientEmailId { get; set; }

    public DateTime? LastUpdated { get; set; }
}

尝试使用 ExecuteSqlRawAsync。没用,它返回的可能是执行计数

c# .net linq-to-entities
1个回答
0
投票

正如 @madreflection 的评论中所建议的,惯用的解决方案是让 EF Core 承担繁重的工作:

var totalCount = await _dbContext.Workflow.CountAsync();

执行标量查询可以参考文档:

查询标量(非实体)类型(假设 EF Core 7 或更高版本)

© www.soinside.com 2019 - 2024. All rights reserved.