我正在编写一个LINQ到SQL语句,并且我在c#中使用ON子句的正常内部连接的标准语法之后。
如何在LINQ to SQL中表示以下内容:
select DealerContact.*
from Dealer
inner join DealerContact on Dealer.DealerID = DealerContact.DealerID
我正在编写一个LINQ到SQL语句,并且我在c#中使用ON子句的正常内部连接的标准语法之后。
如何在LINQ to SQL中表示以下内容:
select DealerContact.*
from Dealer
inner join DealerContact on Dealer.DealerID = DealerContact.DealerID
当前回答
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);
通过Clever Human扩展表达式链语法答案:
如果你想对两个表中的字段进行过滤或选择,而不是只对其中一个表进行操作,你可以在Join方法的最终参数的lambda表达式中创建一个新对象,将这两个表合并在一起,例如:
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记录。
试试这个吧,
var dealer = from d in Dealer
join dc in DealerContact on d.DealerID equals dc.DealerID
select d;
var Data= (from dealer in Dealer join dealercontact in DealerContact on dealer.ID equals dealercontact.DealerID
select new{
dealer.Id,
dealercontact.ContactName
}).ToList();
在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 }