LINQ语句需要优化

时间:2015-02-13 14:21:58

标签: c# linq

我有以下代码

var x = from e in db.Employees
    where e.id == 746
    join f in db.CoWorker on e.CoWorkerID equals f.ID into fa
    from fr in fa.DefaultIfEmpty()
    select new
    {
      e.id,
      e.name,
      coWorkerName = fr.FirstName + " " + fr.LastName
    };

当我在LINQpad中运行该代码时,SQL查询看起来像

SELECT
  [Extent1].[id] AS [id],
  [Extent1].[name] AS [name],
  CASE WHEN ([Extent2].[ID] IS NULL) THEN CASE WHEN ([Extent2].[FirstName] IS NULL) THEN N'' ELSE [Extent2].[LastName] END + N' ' + CASE WHEN ([Extent2].[LastName] IS NULL) THEN N'' ELSE [Extent2].[LastName] END END AS [C1]
FROM  [dbo].[Employees] AS [Extent1]
LEFT OUTER JOIN [dbo].[CoWorker] AS [Extent2] ON [Extent1].[CoWorker] = [Extent2].[ID]
WHERE 1615 = [Extent1].[id]

如何摆脱CASE WHEN阻止?

2 个答案:

答案 0 :(得分:2)

这是一个执行串联客户端的查询。正如你所看到的,它更啰嗦 - 你应该绝对在决定接受之前检查它是否会产生重大影响:

var dbQuery = from e in db.Employees
              where e.id == 746
              join f in db.CoWorker on e.CoWorkerID equals f.ID into fa
              from fr in fa.DefaultIfEmpty()
              select new { e.id, e.name, fr.FirstName, fr.LastName };
var query = dbQuery.AsEnumerable()
                   .Select(x => new {
                       x.id,
                       x.name,
                       coWorkerName = x == null 
                           ? ""
                           : x.FirstName + " " + x.LastName
                   });

答案 1 :(得分:1)

删除coWorkerName = fr.FirstName + " " + fr.LastName表达式,例如,分别选择FirstName和LastName属性,然后再执行连接。此表达式会导致此问题,因为在SQL中将任何内容与NULL结束会产生NULL,但在.net中,NULL会被视为空字符串。

但是,你为什么要这样做?你有证据表明存在问题吗?表达式在预测中,因此不应对查询产生任何重大影响。