我正在编写一个LINQ到SQL语句,并且我在c#中使用ON子句的正常内部连接的标准语法之后。

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

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

当前回答

var Data= (from dealer in Dealer join dealercontact in DealerContact on dealer.ID equals dealercontact.DealerID
select new{
dealer.Id,
dealercontact.ContactName

}).ToList();

其他回答

实际上,在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

在linqc#内连接两个表

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 }

基本上LINQ连接操作符对SQL没有好处。例如,下面的查询

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

将导致内部连接在SQL

join对IEnumerable<>有用,因为它更有效:

from contact in db.DealerContact  

条款将对每个经销商重新执行 但对于IQueryable<>则不是这样。另外,连接也不太灵活。

var data=(from t in db.your tableName(t1) 
          join s in db.yourothertablename(t2) on t1.fieldname equals t2.feldname
          (where condtion)).tolist();

因为我更喜欢表达式链语法,下面是你如何做到这一点:

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