如何使用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个表:公司,地址和地址类型,在此查询中,我必须从公司中选择ID和名称,并通过typename选择2个地址......
答案 0 :(得分:0)
首先通过加入地址和地址类型获取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}
下一步通过加入地址和地址类型获取发票地址列表
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上执行Left Outer Join
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)}
希望它能解决问题。