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

后端 未结 19 1593
感情败类
感情败类 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 05:06

    Actually, often it is better not to join, in linq that is. When there are navigation properties a very succinct way to write your linq statement is:

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

    It translates to a where clause:

    SELECT <columns>
    FROM Dealer, DealerContact
    WHERE Dealer.DealerID = DealerContact.DealerID
    
    0 讨论(0)
  • 2020-11-22 05:07

    Use LINQ joins to perform 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
                       };
    
    0 讨论(0)
  • 2020-11-22 05:07
    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();
    

    Write table names you want, and initialize the select to get the result of fields.

    0 讨论(0)
  • 2020-11-22 05:09

    Inner join two tables in 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 }
    
    0 讨论(0)
  • 2020-11-22 05:11
    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();
    
    0 讨论(0)
  • 2020-11-22 05:14

    Try this :

         var data =(from t1 in dataContext.Table1 join 
                     t2 in dataContext.Table2 on 
                     t1.field equals t2.field 
                     orderby t1.Id select t1).ToList(); 
    
    0 讨论(0)
提交回复
热议问题