【问题标题】:How to perform multiple joins in LINQ如何在 LINQ 中执行多个连接
【发布时间】:2013-06-27 10:04:59
【问题描述】:

我有一个要转换为 LINQ 的存储过程,但我有点卡住了。这是 SQL:

    select 
      @name                             = tp.Name
,     @Entity                           = tc.Entity
,     @Name                             = tc.Name
,     @ID                               =  tpt.ID
,     @Code                             =  tptr.Code  

    from tbltprop tp 

    Left join tblcol tc                                on ( tc.id = tp.ID )
    Left join tblPropday  tpt               on ( tpt.Id = tp.Id )
    Left join tblProperResult tptr   on (tptr.ID = tpt.Id )

    where tp.id               = @chsarpID1 //input ID i get in c#
    and     tpt.Id = @chsarpID2

我了解如何进行单次连接,但在进行多次连接时遇到了一些问题。怎么办?

【问题讨论】:

  • 您对此次转换是否有任何需要我们帮助的具体问题?还是您只是想让我们为您编写代码...
  • 请用 C# 重新编写相同的代码,我不会语法:(,我在 SQL 查询语法方面很笨,对不起,谢谢你的回复
  • 不幸的是 StackOverflow 是一个问答网站,我们倾向于不为人们编写代码。我建议您阅读并了解 LINQ 和 SQL,当然,如果您遇到任何 特定 位问题,请返回。祝你好运!
  • na,我知道 linq sql.. 但我的疑问是如何在 C# 中编写多个连接,单连接我以某种方式学会了但多个连接我不知道:(

标签: c# sql linq sql-to-linq-conversion


【解决方案1】:

这可能对你有帮助......

var values= from tp in tbltprop
            join tb in tblcol ON tp.id equals tb.id into gj
            from gjd in gj.DefaultIfEmpty()
            join tpt in tblPropday ON tp.id equals tpt.id into gk
            from gkd in gk.DefaultIfEmpty()
            join tptr in tblProperResult ON tp.id equals tptr.id into gl
            from gld in gl.DefaultIfEmpty()
            where tp.id == @charpID1 && gkd.Id == @CharpID2
            select new 
                   { 
                       TpName = tp.Name, 
                       Entity = gjd.Entity, 
                       TPTName = gjd.Name, 
                       ID = gkd.ID, 
                       Code = gld.Code
                   };

【讨论】:

  • 您将无法在 select 部分中同时拥有两个名为 Name 的属性。
  • Gopesh,感谢您的回复,如果我在 where 子句中使用 int 会出错,即无法将 int 隐式转换为 bool ?。
  • @LLL 我已经编辑了答案,打字错误,会有两个等号,以前是一个...
  • 感谢 Gopesh,非常感谢,我正在实施这个,感谢您的帮助。
  • 嗨 Gopesh,我不知道如何使用内部选定的 var,即 values.TpName、values.Entity。它没有来,是不是我们需要做一些额外的事情才能访问它们?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-10
  • 1970-01-01
  • 2014-03-13
  • 1970-01-01
  • 2019-06-07
  • 2014-09-17
相关资源
最近更新 更多