简体   繁体   中英

Convert Sql query to linq

hey everyone i want to convert this sql query into linq query. but i have some problem i dont know how to solve it please help me..

my sql query

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

this is tried by me but its have some error please help me to remove this.

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)
                               });

error is

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

Just like how you have done the grouping in your SQL query you need to do in your LINQ query as well like this:-

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)
       });

Your bhh group has a Key and a Collection of items, you should go through this object to get the data. s & si are not valid in the context of your group

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM