【问题标题】:linq multi left join to same propertylinq 多左连接到同一个属性
【发布时间】:2015-08-26 00:45:50
【问题描述】:

是否可以为此查询编写 LINQ? (在 .NET 3.5 中)

select tt.id
     ,tt.detailscount
     ,ttdmx.detailorder
     ,ttdmx.detailtype
     ,ttdm1.detailorder
     ,ttdm1.detailtype
     ,ttdm2.detailorder
     ,ttdm2.detailtype
from test.testtable tt
left join test.testtabledetails ttdmx on tt.id = ttdmx.causeid 
    and tt.maxcausedetailorder = ttdmx.detailorder
left join test.testtabledetails ttdm1 on tt.id = ttdm1.causeid 
    and tt.maxcausedetailorder - 1 = ttdm1.detailorder
left join test.testtabledetails ttdm2 on tt.id = ttdm2.causeid 
    and tt.maxcausedetailorder - 2 = ttdm2.detailorder

类是这样的:

public class Test {
  public int id {get;set;}
  public IList<TestDetails> details {get;set}
}

public class TestDetails {
  public int id {get;set;}
  public int detailOrder {get;set;}
  public int detailType {get;set;}
}

我尝试使用 queryOver,但它不能两次加入同一个属性。

【问题讨论】:

  • 不清楚你在这里的意思。您是否有一个类似的内存集合要编写一个 LINQ 查询,或者您是否有兴趣编写一个可以通过某些 ORM 转换为上述 SQL 的 LINQ 表达式?
  • 我想要一个可以翻译成上面SQL的LINQ表达式。

标签: c# linq entity-framework .net-3.5 left-join


【解决方案1】:

最简单的方法是写:

...
from ttdmx in db.testtabledetails.Where(x => 
    tt.id == x.causeid && 
    tt.maxcausedetailorder == x.detailorder).DefaultIfEmpty()
...

这将被翻译成一个 SQL 左连接

【讨论】:

  • 不幸的是我需要使用 .NET 3.5,所以 .DefaultIfEmpty() 不起作用。不过还是谢谢。我想我需要改变课程
  • 我收到一条错误消息,提示无法识别方法 DefaultIfEmpty stackoverflow.com/questions/8415581/…
  • @intstck 看来你是对的。删除实体框架并改用 Linq to SQL 或升级到较新版本。或者直接执行 SQL,仍然可以将结果映射到 EF 实体。
猜你喜欢
  • 2017-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多