【问题标题】:Linq Optimizing query with records not matching from another tableLinq 使用与另一个表不匹配的记录优化查询
【发布时间】:2016-12-02 06:07:52
【问题描述】:

我有以下查询,它从一个表中提取数据,其中的记录不应该出现在另一个表中。

查询运行良好,但耗时过多,性能受到极大影响。

我可以对此查询进行哪些更改以获得更好的性能,或者我应该以其他方式执行此操作?

var data = (from A in ctx.tblMachine
where
     A.CompanyId == companyId &&
     A.InOutDate >= tempDt &&
     A.InOutDate <= toDate &&
!(from B in ctx.tblEntry
where
     B.CompanyId == companyId &&
     A.EmployeeId == B.EmployeeId &&
     A.InOutDate == B.EntryDate &&
     B.EntryMethod == "M"
select new
{
     B.EmployeeId
}).Contains(new { EmployeeId = A.EmployeeId })
orderby
A.EmployeeId, A.InOutDate select new
{
     A.EmployeeId,
     A.InOutDate,
     A.InOutFlag,
     A.InOutTime
}).ToList();

【问题讨论】:

  • 查看这会产生什么查询并对其进行分析(尝试在 sql 中重新编写它以更快,注意清除缓存)。之后在 linq 中写入更改。如果此结果应在页面中表示,请使用 Skip Take 以仅显示记录的可见部分。
  • 我刚刚在 SQL Server 中转换了上述查询,当我在那里运行时,它在 1 秒内显示了结果。当我在 LINQ 中运行相同的查询时,它需要 20 多分钟。

标签: c# sql-server linq asp.net-mvc-4


【解决方案1】:

您也可以尝试使用连接而不是内部查询...您可以根据需要使用这样的方式进行更改..

var data = (from A in ctx.tblMachine
        join B in ctx.tblEntry on A.EmployeeId == B.EmployeeId &&
                                    A.InOutDate == B.EntryDate &&
                                    B.CompanyId == companyId &&
                                    B.EntryMethod == "M" 
        where
                A.CompanyId == companyId &&
                A.InOutDate >= tempDt &&
                A.InOutDate <= toDate &&
                !(B.EmployeeId).Contains(new { EmployeeId = A.EmployeeId })
        orderby
        A.EmployeeId, A.InOutDate
        select new
        {
            A.EmployeeId,
            A.InOutDate,
            A.InOutFlag,
            A.InOutTime
        }).ToList();

【讨论】:

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