使用join和group by将实体框架查询转换为SQL Server查询

时间:2016-12-16 12:35:50

标签: sql-server entity-framework

我在将linq查询转换为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();

2 个答案:

答案 0 :(得分:0)

如果您尝试从Linq转换为SQL查询,请使用以下

var blogs = context.Blogs.SqlQuery(“SELECT * FROM dbo.Blogs”)。ToList();

价:

https://msdn.microsoft.com/en-us/library/jj592907(v=vs.113).aspx

答案 1 :(得分: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