[英]How to Left join with 2 subselects in Entity Framework Linq?
如何使用Entity Framework在C#中編寫此查詢?
Select Id, Name, DeliveryAdress, InvoiceAdress from Company
left join (Select Address.CompanyId as CompanyId, Street + ' ' + ZipCode + ' ' + City as DeliveryAdress from Address
join AddressType on AddressType.AddressTypeId = Address.AddressTypeId
where AddressType.Name = 'Delivery') sub1 on sub1.CompanyId = Company.Id
left join (Select Address.CompanyId as CompanyId, Street + ' ' + ZipCode + ' ' + City as InvoiceAdress from Address
join AddressType on AddressType.AddressTypeId = Address.AddressTypeId
where AddressType.Name = 'Invoice') sub2 on sub2.CompanyId = Company.Id
實際上,我有3個表:Company,Address和AdressType,在此查詢中,我必須從Company中選擇ID和Name,並通過typename選擇2個Adresses ...
通過加入Address和AddressTypes首先獲取DeliveryAddresses列表
var deliveryaddresses=
from addr in db.Addresses join (addrtype in
db.AddressTypes.Where(at=>at.Name=="Delivery")) on addr.AddressTypeId equals
addrtype.AddressTypeId select new {CompanyId=addr.CompanyId,
DeliveryAddress= addr.Street + " " + ZipCode + " " + City}
接下來,通過加入Address和AddressTypes獲取發票地址列表
var invoiceaddresses=
from addr in db.Addresses join (addrtype in
db.AddressTypes.Where(at=>at.Name=="Invoice")) on addr.AddressTypeId equals
addrtype.AddressTypeId select new {CompanyId=addr.CompanyId,
InvoiceAddress= addr.Street + " " + ZipCode + " " + City}
然后對DeliveryAddresses和invoiceAddresses執行左外部聯接
var deliveryandinvoiceaddresses=from da in deliveryaddresses join ia in
invoiceaddresses on da.CompanyId equals ia.companyId into addrgroup from ag
in addrgroup.DefaultIfEmpty() select new
{CompanyId=da.CompanyId,DeliveryAddress=da.DeliveryAddress,InvoiceAddress=
(ag==null?string.Empty:ag.InvoiceAddress)}
最后在公司上執行左外連接以及交貨和發票地址外連接的結果
var completelist=from c in db.companys join d in deliveryandinvoiceaddresses
on c.Id equals d.CompanyId into compgroup from cg in
companygroup.DefaultIfEmpty() select new {CompanyId=c.Id,
Name=c.Name,DeliveryAddress=(cg==null?string.Empty:cg.DeliveryAddress),
InvoiceAddress=(cg==null?string.Empty:cg.InvoiceAddress)}
希望它能解決問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.