LINQ语句生成比LinqPad不同的查询 [英] LINQ statement generates different query than LinqPad

查看:195
本文介绍了LINQ语句生成比LinqPad不同的查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的代码,通过LEFT查询一些数据连接:

I have the following code that queries some data via a LEFT JOIN:

Model1 db = new Model1();

db.Database.Log = System.Console.Write;

var x = from e in db.Employees
        where e.id == 746
        join f in db.Company on e.CompanyID equals f.ID into fa
        from fr in fa.DefaultIfEmpty()
        select new
        {
          e.id,
          e.name,
          companyName = fr.name
        };

x.Any(); // to see the query in console



在这里使用Visual Studio的奇才生成的类,以确保该模型和数据库上下文代码是正确的。

The classes used here are generated by Visual Studio Wizards to make sure that the model and DB context code is correct.

当我运行在LINQpad代码SQL查询看起来像

When i run that code in LINQpad the SQL query looks like

SELECT [t0].[id] AS [id], [t0].[name] AS [name], [t1].[name] AS [companyName]
FROM [Employees] AS [t0]
LEFT OUTER JOIN [Company] AS [t1] ON [t0].[CompanyID] = [t1].[ID]
WHERE [t0].[id] = 1615

但是当我运行一个简单的控制台应用程序我碰到下面的神秘查询代码是完全错误的:

But when i run the code in a simple Console Application i get the following cryptic query that is totally wrong:

SELECT 
    CASE WHEN ( EXISTS (SELECT 
        1 AS [C1]
        FROM  [dbo].[Employees] AS [Extent1]
        LEFT OUTER JOIN [dbo].[Company] AS [Extent2] ON ([Extent1].[CompanyID] = [Extent2].[ID]) OR (([Extent1].[CompanyID] IS NULL) AND ([Extent2].[ID] IS NULL))
        WHERE 1615 = [Extent1].[id]
    )) THEN cast(1 as bit) ELSE cast(0 as bit) END AS [C1]
    FROM  ( SELECT 1 AS X ) AS [SingleRowTable1]

我想现在找了几个小时的解决方案和LINQ只是不得到查询权。

I tried to find a solution for hours now and LINQ just doesnt get the query right.

有没有人有同样的问题,并解决它以某种方式?任何帮助深表感谢。

Did anybody have the same issue and solved it somehow? Any help is much appreciated.

推荐答案

该查询看起来正确的给我。该LINQpad查询看起来不一样,因为在你的代码中使用任何()

This query looks correct to me. The LINQpad query looks different, because in your code you use Any().

尝试LINQpad以下查询。它应该表现出同样的SQL语句:

Try the following query in LINQpad. It should show the same sql:

 (from e in Employees
    where e.id == 746
    join f in Company on e.CompanyID equals f.ID into fa
    from fr in fa.DefaultIfEmpty()
    select new
    {
      e.id,
      e.name,
      companyName = fr.name
    }).Any()

要看到在您的控制台正确的查询,你可以使用了ToList()而不是任何()

To see the correct query in your console, you could use ToList() instead of Any()

这篇关于LINQ语句生成比LinqPad不同的查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆