[英]Linq to Sql Inner Join
我正在使用联接将linq写入sql语句。 通过搜索,我到达了以下链接: LINQ to SQL中的内部联接的语法是什么? 这个问题的答案是这样的:
var dealercontacts = from contact in DealerContact
join dealer in Dealer on contact.DealerId equals dealer.ID
select contact;
在此语句中,内部on contact.DealerId equals dealer.ID
用于单个比较语句,即on contact.DealerId equals dealer.ID
但是当我尝试on contact.DealerId equals dealer.ID && contact.Branch equals dealer.Branch
,它不接受第二个比较声明。 请指导我如何拥有这个?
您的模型在实体级别上没有真正的关联吗?
意思是, DealerContact
具有代表关联的Dealer
的属性,而不仅仅是处理id。
您甚至可能不需要手动指定该联接。 怎么样:
var dealercontacts = from contact in DealerContact
where contact.Branch equals contact.Dealer.Branch
select contact;
在Linq to SQL中的多个列上进行连接有点不同。
var query =
from t1 in myTABLE1List // List<TABLE_1>
join t2 in myTABLE1List
on new { t1.ColumnA, t1.ColumnB } equals new { t2.ColumnA, t2.ColumnB }
Linq to Sql Joins可以通过belo代码在多种条件下实现:
var q = (from l1 in lst
join l2 in lst1 on new { prop1 = l1.Property1, prop2 = l1.Property2 }
equals new { prop1 = l2.Property1, prop2 = l2.Property2 }
select l1);
优良作法是给属性赋予别名(例如prop1 = l1.Property1,“ prop1”是Property1的别名),因为有时我们要加入具有不同属性名称的属性,从而给编译时带来错误。
另外,请确保加入Property的类型应与int和int相同。 不一样。
我想你可以从这里得到答案
从链接复制并粘贴
var query = from s in context.ShoppingMalls
join h in context.Houses
on
new { s.CouncilCode, s.PostCode }
equals
new { h.CouncilCode, h.PostCode }
select s;
您需要在两个键之间为Id
创建匿名对象,为EqualityComparer
创建Branch
。
linq语法方法:
var dealercontacts = from contact in contacts
join dealer in dealers
on new { Id = contact.DealerId, contact.Branch }
equals new { Id = dealer.ID, dealer.Branch }
select contact;
Lambda方法:
var dealercontacts = contacts.Join(dealers,
contact => new { Id = contact.DealerId, contact.Branch },
dealer => new { Id = dealer.ID, dealer.Branch },
(contact, dealer) => contact);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.