将存储过程sql转换为linq

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

我创建了以下存储过程:

PROCEDURE [dbo].[LeadScoring_CountClosedActions]
(
        @UserId INT,
        @StartDate INT,
        @EndDate INT
)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON

    -- Insert statements for procedure here
    SELECT 
            TOP 1 COUNT(l.Extra) OVER () AS TotalRecords
        FROM [dbo].[LeadScoringActions] AS a
            INNER JOIN [dbo].[LeadScoringLeads] AS l ON a.LeadId = l.LeadId
        WHERE a.AssignedToUserId = @UserId 
            AND a.DateCompleted > DATEADD(DAY, @StartDate, GETDATE())
            AND a.DateCompleted <= DATEADD(DAY, @EndDate, GETDATE())
            AND a.ActionResultType != 'System Closed'
            AND l.Extra IS NOT NULL
        GROUP BY l.Extra
END

我试图在 ef core 中使用以下命令来执行它:

var count = await _context.Database.ExecuteSqlRawAsync($"exec LeadScoring_CountClosedActions @UserId={userId}, @StartDate={request.StartDate}, @EndDate={request.EndDate}");

但它总是返回 -1,所以我环顾四周,似乎我应该将存储过程转换为 linq(请参阅这个问题的评论之一)

我想知道我会怎么做 - 我知道如何做一般的事情:

            var count = await _context
                .Actions
                    .Include(a => a.Lead)
                .CountAsync(a =>
                    a.ActionResultType != LeadScoringConstants.SystemClosed &&
                    a.DateCompleted > DateTime.Today.AddDays(request.StartDate) &&
                    a.DateCompleted <= DateTime.Today.AddDays(request.EndDate) &&
                    a.AssignedToUserId == userId &&
                    a.Lead.Extra != null);

但我不确定如何执行

GROUP BY
- 在 linq 中,它将按
a.Lead.Extra
分组,或者是否可以执行
COUNT OVER

将其作为 linq 更好还是有办法执行存储过程并获得正确的结果?

c# entity-framework stored-procedures entity-framework-core
1个回答
0
投票

最后我使用 linq 通过从数据库获取匹配操作来解决它,然后我从结果中获得了不同的额外属性并计算了它们:

var actions = await _context
                .Actions
                    .Include(a => a.Lead)
                .Where(a =>
                    a.ActionResultType != LeadScoringConstants.SystemClosed &&
                    a.DateCompleted > DateTime.Today.AddDays(request.StartDate) &&
                    a.DateCompleted <= DateTime.Today.AddDays(request.EndDate) &&
                    a.AssignedToUserId == userId &&
                    a.Lead.Extra != null)
                .ToListAsync();

var projectIds = actions.Select(a => a.Lead.Extra).Distinct().Count();
© www.soinside.com 2019 - 2024. All rights reserved.