将具有连接和联合的多个连接的SQL查询转换为LINQ?

时间:2015-02-26 15:42:43

标签: c# sql-server linq entity-framework

我正在尝试编写一个LINQ查询,该查询从5个不同的实体收集信息,并相应地创建其信息列表。不幸的是,虽然我可以让查询在SQL中工作,但我有点不确定如何让它在LINQ中工作。

基本上,我正在尝试获取所有资产的列表(分布在两个表中)。然后,我需要转到我们的AssetActions实体,并确保对特定资产执行的最后一个操作是签到或确保它从未在跟踪中输入过。

我有一个名为DeviceTypes的决赛桌。只有我的一个资产表使用此功能,另一个只是自动分配值Phone

我的SQL查询是:

SELECT comp.id, 
       dType.devicetypename, 
       comp.notes 
FROM   asset.computer comp 
       LEFT OUTER JOIN asset.devicetype dType 
                    ON dType.id = comp.devicetypeid 
       LEFT OUTER JOIN (SELECT t1.computerid, 
                               t1.id, 
                               t1.assetactionid 
                        FROM   asset.computertracking t1 
                               JOIN (SELECT Max(id) id, 
                                            computerid 
                                     FROM   asset.computertracking 
                                     GROUP  BY computerid) t2 
                                 ON t1.id = t2.id) track 
                    ON comp.id = track.computerid 
WHERE  track.assetactionid = 1 
        OR comp.id NOT IN(SELECT computerid 
                          FROM   asset.computertracking) 
UNION 
SELECT phone.id, 
       'Phone' AS devicetypename, 
       phone.notes 
FROM   asset.phone phone 
       LEFT OUTER JOIN (SELECT t1.phoneid, 
                               t1.id, 
                               t1.assetactionid 
                        FROM   asset.phonetracking t1 
                               JOIN (SELECT Max(id) id, 
                                            phoneid 
                                     FROM   asset.phonetracking 
                                     GROUP  BY phoneid) t2 
                                 ON t1.id = t2.id) track 
                    ON phone.id = track.phoneid 
WHERE  track.assetactionid = 1 
        OR phone.id NOT IN(SELECT phoneid 
                           FROM   asset.phonetracking) 

我的一个LINQ测试是:

availableAssets =   from comp in db.Computers
                    join compType in db.DeviceTypes
                    on comp.DeviceTypeId equals compType.Id
                    join track in db.ComputerTrackings
                    on comp.Id equals track.ComputerId into comp2
                    from track2 in comp2.DefaultIfEmpty()
                    where track2 == null || track2.AssetActionId == 1
                    select new AvailableAsset {
                        assetName = comp.Id.ToString(),
                        assetType = compType.DeviceTypeName,
                        assetNotes = comp.Notes
                    };

LINQ查询的主要问题是,虽然它确实选择了正确的资产,但它不处理已进入两次跟踪的资产。如果有东西被检查出来。然后办理登机手续。然后检查回来,它不会理解抓住最后输入的记录。

旁注。如果有任何方法可以修改查询以返回assetName字段的格式化ID,那将非常感激。例如,它现在返回1, 2, 3, 4...。我希望它返回LHE-001, LHE-002...,而手机会返回LHE-TEL-001, LHE-TEL-002...

0 个答案:

没有答案