将Sql查询转换为linq

时间:2015-04-13 11:36:06

标签: c# sql-server linq

嘿大家我想把这个sql查询转换成linq查询。但我有一些问题,我不知道如何解决它,请帮助我..

我的SQL查询

select SERVICESLASBYCOUNTRY.id,site.Name, SERVICESLASBYCOUNTRY.countrycode, sum(SERVICESLASBYCOUNTRYDETAILS.estddays) as estddays
from SERVICESLASBYCOUNTRY
inner join site on SERVICESLASBYCOUNTRY.SiteId = site.id
inner join SERVICESLASBYCOUNTRYDETAILS on SERVICESLASBYCOUNTRY.id = SERVICESLASBYCOUNTRYDETAILS.servicelasbycountrykey
where SERVICESLASBYCOUNTRY.servicecode = 234
group by SERVICESLASBYCOUNTRYDETAILS.servicelasbycountrykey,site.Name, SERVICESLASBYCOUNTRY.countrycode,SERVICESLASBYCOUNTRY.id

这是我尝试但它有一些错误请帮我删除它。

from s in db.SERVICESLASBYCOUNTRies
                               join si in db.sites on s.SiteId equals si.id
                               join sd in db.SERVICESLASBYCOUNTRYDETAILs on s.id equals sd.servicelasbycountrykey 
                               where s.servicecode == servicecode
                               group sd by sd.estddays into bhh 
                               select new SLACountryDTO                        
                               {
                                   ID = s.id,
                                   ServiceCode = s.servicecode,
                                   CountryCode = s.countrycode,
                                   SiteId = s.SiteId,
                                   SiteName = si.Name,
                                   Sum = bhh.Sum(sd => sd.estddays)
                               });

错误是

"s" does not exist current context 
"si" does not exist current context

2 个答案:

答案 0 :(得分:2)

就像你在SQL查询中完成grouping一样,你需要在你的LINQ查询中做到这样: -

from s in db.SERVICESLASBYCOUNTRies
      join si in db.sites on s.SiteId equals si.id
      join sd in db.SERVICESLASBYCOUNTRYDETAILs on s.id equals sd.servicelasbycountrykey 
      where s.servicecode == servicecode
      group sd by new { sd.estddays, s.countrycode,s.servicecode,s.id,s.SiteId,si.Name } 
                  into bhh 
      select new SLACountryDTO                        
      {
           ID = bhh.Key.id,
           ServiceCode = bhh.Key.servicecode,
           CountryCode = bhh.Key.countrycode,
           SiteId = bhh.Key.SiteId,
           SiteName = bhh.Key.Name,
           Sum = bhh.Sum(sd => sd.estddays)
       });

答案 1 :(得分:0)

你的bhh组有一个Key和一个项目集合,你应该通过这个对象来获取数据。 s& si在您的小组环境中无效