2015-09-10 115 views
-3

我有這樣的內部聯接查詢:如何將SQL JOIN查詢轉換爲c#LINQ to Entity?

Select Clients.ClientName, 
     InspectionAuthorities.Description, 
     COUNT(DISTINCT ObjectTypes.Description) AS NumberOfObjectTypes 
From InspectionArchives 
--Customer-- 
Inner Join Clients On InspectionArchives.CustomerID = Clients.Id 
--Inspection Authority-- 
Inner Join InspectionAuthorityInspectionArchives On InspectionArchives.Id = InspectionAuthorityInspectionArchives.InspectionArchive_Id 
Inner Join InspectionAuthorities On InspectionAuthorityInspectionArchives.InspectionAuthority_Id = InspectionAuthorities.Id 
--Object Types-- 
Inner Join ObjectTypeInspectionArchives On InspectionArchives.Id = ObjectTypeInspectionArchives.InspectionArchive_Id 
Inner Join ObjectTypes On ObjectTypeInspectionArchives.ObjectType_Id = ObjectTypes.Id 
Where Clients.Id = 1 or Clients.Id = 2 
Group by Clients.ClientName, InspectionAuthorities.Description; 

我新來的LINQ世界,需要上面的SQL查詢轉換爲C#LINQ到實體。

任何想法如何實現它?

+5

首先,您至少應該展示一個嘗試自己轉換它。第二次閱讀[this](https://coding.abel.nu/2012/06/dont-use-linqs-join-navigate/)並學習如何使用EF爲您創建的導航屬性。 – juharr

回答

1
from IA in contextObj.InspectionArchives 
join cl in contextObj.Clients on IA.CustomerID equals Cl.Id 
join IaIa in contextObj.InspectionAuthorityInspectionArchives On IA.Id equals IaIa .InspectionArchive_Id 
join IAuth in contectObj.InspectionAuthorities on IaIa.InspectionAuthority_Id equals IAuth.Id 
join OTIA in contextObj.ObjectTypeInspectionArchives on IA.Id equals OTIA.InspectionArchive_Id 
join ObjT in contextObj.ObjectTypes on OTIA.ObjectType_Id equals ObjT.Id 
where (Cl.Id = 1 || Cl.Id = 2) 
group new {cl, IAuth} by new {Cl.ClientName, IAuth.Description} into grp 
select new 
{ 
    clientName = grp.key.ClientName, 
    Desc = grp.key.Description, 
    NumberOfObjectTypes = grp.Count(g=>g.ObjT.Description.Distinct()) 
};