【问题标题】:What is the syntax for an inner join in LINQ to SQL?LINQ to SQL 中的内部联接的语法是什么?
【发布时间】:2010-09-07 10:19:20
【问题描述】:

我正在编写一个 LINQ to SQL 语句,并且我正在使用 C# 中带有 ON 子句的普通内部联接的标准语法。

您如何在 LINQ to SQL 中表示以下内容:

select DealerContact.*
from Dealer 
inner join DealerContact on Dealer.DealerID = DealerContact.DealerID

【问题讨论】:

  • 如果表之间有外键,您应该在下面查看 Kirk Broadhurst 的答案。
  • 你应该复数你的表名。一张包含(关于)许多经销商的桌子应该称为经销商,而不是经销商。
  • @ANeves 使用复数表名远非标准做法,单数和复数都是完全可以接受的-我自己只是从复数切换到单数以匹配对象名称-这里的最佳答案同意单数更多一致(许多复数形式很奇怪或不存在 - 例如,'1 只羊,8 只羊':stackoverflow.com/questions/338156/…
  • @niico 这不是讨论这个的地方,我猜...但是 Microsoft Entity Framework pluralizes the table names,Ruby on Rails 的 ORM pluralizes the tables... 足够接近标准 -为你练习? :) 反驳:NHibernate seems to not pluralize tables.
  • 确实 - 有些人以一种方式做事 - 有些人以另一种方式做事。没有标准做法。我个人认为单数有更多的好处。

标签: c# .net sql linq-to-sql join


【解决方案1】:

它是这样的:

from t1 in db.Table1
join t2 in db.Table2 on t1.field equals t2.field
select new { t1.field2, t2.field3}

如果您的表具有合理的名称和字段以作为更好的示例,那就太好了。 :)

更新

我认为对于您的查询,这可能更合适:

var dealercontacts = from contact in DealerContact
                     join dealer in Dealer on contact.DealerId equals dealer.ID
                     select contact;

因为您是在寻找联系人,而不是经销商。

【讨论】:

  • 谢谢,从现在开始,我将使用 sensible names 作为最佳实践,这在 linq 中是有意义的,而不是 from c or from t1
  • 我过去曾多次使用过 linq 连接,但遇到了一个我以前从未见过的问题,因为您在 VS 中看到的错误并不完全清楚:当您编写ON 语句必须首先引用 FROM 表。你可以说on t1.field equals t2.field,但你不能写on t2.field equals t1.field,因为在这种情况下编译器不会理解t2 指的是什么。
【解决方案2】:

因为我更喜欢表达式链语法,所以你可以这样做:

var dealerContracts = DealerContact.Join(Dealer, 
                                 contact => contact.DealerId,
                                 dealer => dealer.DealerId,
                                 (contact, dealer) => contact);

【讨论】:

  • 如果您需要过滤或选择 both 连接表中的字段,而不仅仅是两个表之一的字段(此答案示例中的 DealerContact 表),这是一个例子:stackoverflow.com/a/29310640/12484
【解决方案3】:

通过 Clever Human 扩展表达式链语法answer

如果您想对连接在一起的两个表中的字段执行操作(如过滤或选择)——而不是仅在这两个表中的一个上——您可以在最后一个参数的 lambda 表达式中创建一个新对象以合并这两个表的 Join 方法,例如:

var dealerInfo = DealerContact.Join(Dealer, 
                              dc => dc.DealerId,
                              d => d.DealerId,
                              (dc, d) => new { DealerContact = dc, Dealer = d })
                          .Where(dc_d => dc_d.Dealer.FirstName == "Glenn" 
                              && dc_d.DealerContact.City == "Chicago")
                          .Select(dc_d => new {
                              dc_d.Dealer.DealerID,
                              dc_d.Dealer.FirstName,
                              dc_d.Dealer.LastName,
                              dc_d.DealerContact.City,
                              dc_d.DealerContact.State });

有趣的部分是该示例第 4 行中的 lambda 表达式:

(dc, d) => new { DealerContact = dc, Dealer = d }

...在这里我们构造了一个新的匿名类型对象,该对象具有 DealerContact 和 Dealer 记录以及它们的所有字段作为属性。

然后,我们可以在过滤和选择结果时使用这些记录中的字段,如示例的其余部分所示,该示例使用 dc_d 作为我们构建的匿名对象的名称,该对象同时具有 DealerContact 和 Dealer 记录作为它的属性。

【讨论】:

  • 使用 lambda 的联接语法很糟糕。我拒绝使用它;-)
  • @aristo 我一点也不怪你。我通常不得不参考这篇文章来提醒自己语法!
  • 像我这样的人更喜欢一致性。这就是我专门搜索 lambda 语法的原因。
【解决方案4】:
var results = from c in db.Companies
              join cn in db.Countries on c.CountryID equals cn.ID
              join ct in db.Cities on c.CityID equals ct.ID
              join sect in db.Sectors on c.SectorID equals sect.ID
              where (c.CountryID == cn.ID) && (c.CityID == ct.ID) && (c.SectorID == company.SectorID) && (company.SectorID == sect.ID)
              select new { country = cn.Name, city = ct.Name, c.ID, c.Name, c.Address1, c.Address2, c.Address3, c.CountryID, c.CityID, c.Region, c.PostCode, c.Telephone, c.Website, c.SectorID, Status = (ContactStatus)c.StatusID, sector = sect.Name };


return results.ToList();

【讨论】:

  • 嗨,你能告诉我这部分是关于什么的吗? Status = (ContactStatus)c.StatusID 我对片段特别感兴趣:(ContactStatus)c.StatusID Regards Mariusz
  • @aristo - 查看代码,我猜ContactStatus 确实是一个枚举,而c.StatusID 并不是真正的ID,而是枚举的数值。如果我是对的,(ContactStatus)c.StatusID 实际上只是将整数转换为枚举。
【解决方案5】:

您创建一个外键,LINQ-to-SQL 为您创建导航属性。每个Dealer 都会有一个DealerContacts 的集合,您可以选择、过滤和操作它们。

from contact in dealer.DealerContacts select contact

context.Dealers.Select(d => d.DealerContacts)

如果您不使用导航属性,那么您将错过 LINQ-to-SQL 的主要优势之一 - 映射对象图的部分。

【讨论】:

  • 天哪,你节省了我的时间,我不需要再处理这些愚蠢的连接了!
【解决方案6】:

使用Linq Join 运算符:

var q =  from d in Dealer
         join dc in DealerConact on d.DealerID equals dc.DealerID
         select dc;

【讨论】:

  • 当我想要 d 和 dc 的列时该怎么办?
  • @KuntadyNithesh 然后返回您创建的类,例如 select new MyCustomer{ Id = dc.id, Id2 = d.id } 就是这样!
【解决方案7】:

基本上 LINQ join 运算符对 SQL 没有任何好处。 IE。以下查询

var r = from dealer in db.Dealers
   from contact in db.DealerContact
   where dealer.DealerID == contact.DealerID
   select dealerContact;

将导致 SQL 中的 INNER JOIN

join 对 IEnumerable 很有用,因为它更高效:

from contact in db.DealerContact  

条款将为每个经销商重新执行 但对于 IQueryable 情况并非如此。 join 也不太灵活。

【讨论】:

    【解决方案8】:

    实际上,在 linq 中,通常最好不要加入。当有导航属性时,编写 linq 语句的一种非常简洁的方法是:

    from dealer in db.Dealers
    from contact in dealer.DealerContacts
    select new { whatever you need from dealer or contact }
    

    翻译成where子句:

    SELECT <columns>
    FROM Dealer, DealerContact
    WHERE Dealer.DealerID = DealerContact.DealerID
    

    【讨论】:

    • 在表达式链语法中具有多个“from”子句(如本例)的 LINQ 查询是什么样的?有可能吗?
    • 它的方法语法等价于SelectMany()
    【解决方案9】:

    linq C#中的两个表的内连接

    var result = from q1 in table1
                 join q2 in table2
                 on q1.Customer_Id equals q2.Customer_Id
                 select new { q1.Name, q1.Mobile, q2.Purchase, q2.Dates }
    

    【讨论】:

      【解决方案10】:

      使用LINQ joins 执行Inner Join。

      var employeeInfo = from emp in db.Employees
                         join dept in db.Departments
                         on emp.Eid equals dept.Eid 
                         select new
                         {
                          emp.Ename,
                          dept.Dname,
                          emp.Elocation
                         };
      

      【讨论】:

        【解决方案11】:

        试试这个:

             var data =(from t1 in dataContext.Table1 join 
                         t2 in dataContext.Table2 on 
                         t1.field equals t2.field 
                         orderby t1.Id select t1).ToList(); 
        

        【讨论】:

          【解决方案12】:
          var q=(from pd in dataContext.tblProducts join od in dataContext.tblOrders on pd.ProductID equals od.ProductID orderby od.OrderID select new { od.OrderID,
           pd.ProductID,
           pd.Name,
           pd.UnitPrice,
           od.Quantity,
           od.Price,
           }).ToList(); 
          

          【讨论】:

          • 欢迎来到 Stack Overflow!虽然这段代码 sn-p 可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您正在为将来的读者回答问题,而这些人可能不知道您的代码建议的原因。也请尽量不要用解释性 cmets 挤满你的代码,因为这会降低代码和解释的可读性!
          【解决方案13】:
          OperationDataContext odDataContext = new OperationDataContext();    
                  var studentInfo = from student in odDataContext.STUDENTs
                                    join course in odDataContext.COURSEs
                                    on student.course_id equals course.course_id
                                    select new { student.student_name, student.student_city, course.course_name, course.course_desc };
          

          学生和课程表有主键和外键关系的地方

          【讨论】:

            【解决方案14】:

            试试这个,

            var dealer = from d in Dealer
                         join dc in DealerContact on d.DealerID equals dc.DealerID
                         select d;
            

            【讨论】:

              【解决方案15】:
              var Data= (from dealer in Dealer join dealercontact in DealerContact on dealer.ID equals dealercontact.DealerID
              select new{
              dealer.Id,
              dealercontact.ContactName
              
              }).ToList();
              

              【讨论】:

                【解决方案16】:
                var data=(from t in db.your tableName(t1) 
                          join s in db.yourothertablename(t2) on t1.fieldname equals t2.feldname
                          (where condtion)).tolist();
                

                【讨论】:

                  【解决方案17】:
                  var list = (from u in db.Users join c in db.Customers on u.CustomerId equals c.CustomerId where u.Username == username
                     select new {u.UserId, u.CustomerId, u.ClientId, u.RoleId, u.Username, u.Email, u.Password, u.Salt, u.Hint1, u.Hint2, u.Hint3, u.Locked, u.Active,c.ProfilePic}).First();
                  

                  写你想要的表名,初始化select得到字段的结果。

                  【讨论】:

                  • var list = (from u in db.Yourfirsttablename join c in db.secondtablename on u.firsttablecommonfields equals c.secondtablecommon field where u.Username == username select new {u.UserId, u.CustomerId , u.ClientId, u.RoleId, u.Username, u.Email, u.Password, u.Salt, u.Hint1, u.Hint2, u.Hint3, u.Locked, u.Active,c.ProfilePic}) .First();
                  【解决方案18】:

                  从 DealerContrac 中的 d1 在 d1.dealearid 上加入 DealerContrac 中的 d2 等于 d2.dealerid 选择新的 {dealercontract.*}

                  【讨论】:

                  • 欢迎来到 Stack Overflow!此答案不会对现有答案增加任何内容。
                  【解决方案19】:

                  一个最好的例子

                  表名:TBL_EmpTBL_Dep

                  var result = from emp in TBL_Emp join dep in TBL_Dep on emp.id=dep.id
                  select new
                  {
                   emp.Name;
                   emp.Address
                   dep.Department_Name
                  }
                  
                  
                  foreach(char item in result)
                   { // to do}
                  

                  【讨论】:

                    猜你喜欢
                    • 2011-03-11
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2012-10-24
                    相关资源
                    最近更新 更多