What is the syntax for an inner join in LINQ to SQL?

后端 未结 19 1630
感情败类
感情败类 2020-11-22 04:25

I\'m writing a LINQ to SQL statement, and I\'m after the standard syntax for a normal inner join with an ON clause in C#.

How do you represent the follo

相关标签:
19条回答
  • 2020-11-22 04:51

    It goes something like:

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

    It would be nice to have sensible names and fields for your tables for a better example. :)

    Update

    I think for your query this might be more appropriate:

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

    Since you are looking for the contacts, not the dealers.

    0 讨论(0)
  • 2020-11-22 04:55

    try instead this,

    var dealer = from d in Dealer
                 join dc in DealerContact on d.DealerID equals dc.DealerID
                 select d;
    
    0 讨论(0)
  • 2020-11-22 04:55

    One Best example

    Table Names : TBL_Emp and TBL_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}
    
    0 讨论(0)
  • 2020-11-22 04:57

    from d1 in DealerContrac join d2 in DealerContrac on d1.dealearid equals d2.dealerid select new {dealercontract.*}

    0 讨论(0)
  • 2020-11-22 04:58

    And because I prefer the expression chain syntax, here is how you do it with that:

    var dealerContracts = DealerContact.Join(Dealer, 
                                     contact => contact.DealerId,
                                     dealer => dealer.DealerId,
                                     (contact, dealer) => contact);
    
    0 讨论(0)
  • 2020-11-22 04:58
    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 };
    

    Where student and course tables have primary key and foreign key relationship

    0 讨论(0)
提交回复
热议问题