2016-12-16 171 views
0

將linq查詢轉換爲SQL Server查詢時遇到問題。將實體框架查詢轉換爲SQL Server查詢

var gdevices = (from logs in dbContext.GensetLogs 
       group logs by logs.DeviceId into logsgroup 
       join devices in dbContext.GensetDevices on logsgroup.FirstOrDefault().DeviceId equals devices.Id 
       where devices.RegisteredBy == model.Email || devices.OperatedBy == model.Email || model.StType == "admin" 
       select new DeviceRegistrationDTO 
          { 
           PhoneNumber = devices.PhoneNumber, 
           Latitude = devices.Latitude, 
           Longitude = devices.Longitude, 
           LatestRT = logsgroup.Max(d => d.ReadingTime), 
           DeviceName = logsgroup.Max(d => d.ReadingTime).DeviceName, 
           OperatedBy = devices.OperatedBy, 
           ThresholdValue = devices.ThresholdValue 
          }).ToList(); 
+3

轉換爲純SQL?嗯,不知道你爲什麼要這樣做,但用'ToString'替換'ToList'並且有你的SQL查詢。 –

+0

[如何查看由實體框架生成的SQL?](http://stackoverflow.com/questions/1412863/how-do-i-view-the-sql-generated-by-the-entity -framework) – Igor

回答

0

我非常簡單的方式做到了這一點。

SELECT (t.[TransId]) 
    , t.[SGCode] 
    , t.PurchaseDate 
    , t.SoldTo 
     ,t.Cost 
    ,(select top 1 dr.Rate from DepreciationRate dr where t.Assets_TransId = dr.Assets_TransId order by dr.DepDate desc) Rate 
    ,(select sc.Name from AssetsSubClass sc where t.SubClass_TransId = sc.TransId) Name 

FROM AssetsTransctions t