转换具有多个表的SQL查询并联接到LINQ查询

时间:2018-10-31 12:48:19

标签: c# sql-server linq

我有一个已设法在SQL Server中运行但无法在LINQ中运行的查询。 SQL表有多个联接,但是有一个表不是包含数据的联接,我认为这是我的LINQ查询失败的地方。

该代码在Visual Studio中可以正常编译,但是在运行查询时会崩溃。这是我的SQL:

SELECT DISTINCT TOP (1000) 
MA_MASTER.YEAR_ID,
PC_PARCEL.P_ID, 
PC_PARCEL.TAX_MAP, 
PC_PARCEL.LEGAL_INDEX,
ISNULL(NULLIF(PC_ADDRESS.FORMATED_ADDRESS, ''), 'Unknown Address') AS FORMATED_ADDRESS,
OWNR.NA_ID, 
NA_NAMES.NAME_INDEX,
MA_MASTER.INSP_FLAG,
IIF(MA_MASTER.INSP_FLAG IS NULL, NULL, 
  (SELECT TOP 1 [GOVERNPORTALDEV].[dbo].[VT_USER].[LONG_DESC_EN] 
  FROM [GOVERNPORTALDEV].[dbo].[VT_USER] 
  WHERE MA_MASTER.INSP_FLAG = [GOVERNPORTALDEV].[dbo].[VT_USER].[CODE] 
  AND TABLE_NAME like '%ins_flag%')) AS [LONG_DESC_EN]
FROM ((GOVERNPORTALDEV.dbo.PC_PARCEL 
INNER JOIN GOVERNPORTALDEV.dbo.PC_ADDRESS
  ON GOVERNPORTALDEV.dbo.PC_PARCEL.P_ID = 
GOVERNPORTALDEV.dbo.PC_ADDRESS.P_ID) 
INNER JOIN (SELECT P_ID, Min(NA_ID) AS NA_ID FROM 
GOVERNPORTALDEV.dbo.PC_OWNER GROUP BY P_ID) AS OWNR
  ON GOVERNPORTALDEV.dbo.PC_PARCEL.P_ID = OWNR.P_ID) 
INNER JOIN GOVERNPORTALDEV.dbo.NA_NAMES 
  ON OWNR.NA_ID = GOVERNPORTALDEV.dbo.NA_NAMES.NA_ID
INNER JOIN GOVERNPORTALDEV.dbo.MA_MASTER
  ON GOVERNPORTALDEV.dbo.MA_MASTER.P_ID = GOVERNPORTALDEV.dbo.PC_PARCEL.P_ID
,[GOVERNPORTALDEV].[dbo].[VT_USER] 
WHERE [GOVERNPORTALDEV].[dbo].[PC_PARCEL].[JURISDICTION] ='MANKO' 
  AND MA_MASTER.YEAR_ID = 2018
  AND TABLE_NAME like '%ins_flag%'
  AND FROZEN_ID = 0
ORDER BY P_ID;

这是我的LINQ查询:

var query = from pc_parcel in Context.PC_PARCEL
    join pc_address in Context.PC_ADDRESS 
      on pc_parcel.P_ID equals pc_address.P_ID
    join ownr in Context.PC_OWNER.GroupBy(pid => new { pid.P_ID, pid.NA_ID })
      .Select(ownr => new { ownr.Key.P_ID, NA_ID = ownr.Min(m => m.NA_ID) })
                      on pc_parcel.P_ID equals ownr.P_ID
    join na_names in Context.NA_NAMES
      on ownr.NA_ID equals na_names.NA_ID
    join ma_master in Context.MA_MASTER
      on pc_parcel.P_ID equals ma_master.P_ID
    join vt_user in Context.VT_USER
      on ma_master.INSP_FLAG equals vt_user.CODE

    where pc_parcel.JURISDICTION == juris_code && 
      ma_master.YEAR_ID == year && 
      ma_master.FROZEN_ID == 0 && 
      vt_user.TABLE_NAME.Contains("ins_flag")
    orderby pc_parcel.P_ID

    select new MaintenanceListDetail
    {
        AssessmentID = pc_parcel.TAX_MAP,
        LegalLandDescription = pc_parcel.LEGAL_INDEX,
        CivicAddress = pc_address.FORMATED_ADDRESS,
        ReasonForInspection = null,
        OwnerName = na_names.NAME_INDEX,
        OwnerEmail = null,
        OwnerPhone = null,
        Status = 0
    };

我将问题Creating a LINQ select from multiple tables用作代码的基础,但无法使其正常工作。

0 个答案:

没有答案