简体   繁体   English

将带有where子句的左外连接转换为Linq-to-sql

[英]Conversion Of left Outer join with a where clause to Linq-to-sql

Below I have two queries. 下面我有两个查询。 I have a Sql Query and a linq query I have been tinkering with. 我已经修改过一个Sql查询和linq查询。 I have not be able to get the linq query to be logically equivalent to the sql query. 我无法使linq查询在逻辑上等同于sql查询。 My current issue exists on the line with the following comment //right here . 我当前的问题在线上带有以下注释//right here

I am getting a compile error trying to access u.isDeleted : 我在尝试访问u.isDeleted时遇到编译错误:

The name 'u' does not exist in the current context 名称“ u”在当前上下文中不存在

Can someone tell me why and help me fix the query to compile please. 有人可以告诉我原因,请帮助我修复查询进行编译。 If this isn't an optimal way of doing it, I am open to suggestions. 如果这不是最佳方法,我欢迎您提出建议。 Thank you very much!!!! 非常感谢你!!!!

Linq (which doesn't work) Linq(无效)

var ret = (from m IN db.Foo
           join u in db.Bar on m.Id equals u.m_Id
           into FooBars
           from vm IN db.Temp.DefaultIfEmpty()
           where  vm == null && u.Id = 32 // right here
           select m).ToList();

Sql Query, which I would like to convert to linq SQL查询,我想将其转换为linq

SELECT m.*
FROM Foo AS m
INNER JOIN Bar AS u ON m.Id = u.m_Id
LEFT JOIN Temp AS vm on u.M_Id = temp.m_Id
WHERE vm.id IS NULL AND u.Id = 32

I think you got the left join syntax wrong. 我认为您left join语法错误。 This is how: 这是这样的:

var ret = (from m IN db.Foo
           join u in db.Bar on m.Id equals u.m_Id
           join vm in db.Temp on u.M_Id = temp.m_Id into vmg
           from vm im vmg.DefaultIfEmpty()
           where vm == null && u.IsDeleted
           select m).ToLIST();
  • The into X syntax is GroupJoin method - so you are using it wrong when joining to db.Bar - there you want a normal join into X语法是GroupJoin方法-因此在连接到db.Bar时使用了错误的db.Bar -您需要普通的连接
  • When performing a left join you first use a GroupJoin and then you select from the group adding DefaultIfEmpty . 执行左联接时,首先使用GroupJoin ,然后从添加DefaultIfEmpty的组中进行选择。

See documentation of Left Join - it shows both in query syntax like above and also in method syntax (and uses GroupJoin ) 请参阅Left Join的文档-它以上述查询语法和方法语法显示(并使用GroupJoin


As for your compile error: 至于你的编译错误:

The name 'u' does not exist in the current context 名称“ u”在当前上下文中不存在

Your query: 您的查询:

var ret = (from m IN db.Foo
    join u in db.Bar on m.Id equals u.m_Id
    into FooBars
    from vm IN db.Temp.DefaultIfEmpty()
    where  vm == null && u.Id = 32 // right here
    select m ).ToList();

Reason being is that you grouped all the results of the join to FooBars - so after that line there is no such thing as u in your query 原因是您将所有FooBarsFooBars的结果分组了-因此,在该行之后,查询中没有诸如u类的东西

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM