how to write this query in c# with Entity Framework?
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
In Fact I have 3 Tables: Company, Address and AdressType and in this query I have to select the ID and Name from the Company and 2 Adresses selected by typename...
First Get List Of DeliveryAddresses by joining Address and AddressTypes
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}
Next Get List Of Invoice Addresses by joining Address and 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}
Then Perform Left Outer Join On DeliveryAddresses and 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)}
Finally Perform Left Outer Join on Company and the result of outer join of delivery and invoice addresses
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)}
Hope it solves the problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.