Search code examples
sql-serverlinq

Use LINQ Query Operations


Please need assistance to convert this SQl Query to LINQ Query

SELECT EconCode.EconCodeId, 
       EconCode.EconCodeName, 
       EconCode.EconIncomeAmt, 
       EconCode.EconRecExpAmt, 
       EconCode.EconCapExpAmt, 
       FundCode.FundCodeId
FROM EconCode 
LEFT OUTER JOIN FundCode 
   ON EconCode.FundCodeId = FundCode.FundCodeId
GROUP BY EconCode.EconCodeId, 
         EconCode.EconCodeName, 
         EconCode.EconIncomeAmt, 
         EconCode.EconRecExpAmt, 
         EconCode.EconCapExpAmt, 
         FundCode.FundCodeId

I have tried the following codes before but but in my report display nothing.

var query = from econ in _context.EconCode
         join fund in _context.FundCode on econ.FundCodeId equals fund.FundCodeId
         group new { econ, fund.FundCodeId } by new { fund.FundCodeName, econ.FundCodeId, econ.EconCodeId, econ.EconCodeName, econ.EconIncomeAmt, econ.EconRecExpAmt, econ.EconCapExpAmt  } into g
          select new
             {
              fundcodeId = g.Key.FundCodeId,
              fundCodeName = g.Key.FundCodeName,
              econCodeId = g.Key.EconCodeId,
              econCodeName = g.Key.EconCodeName,
              econIncomeAmt = g.Key.EconIncomeAmt,
              econRecExpAmt = g.Key.EconRecExpAmt,
              econCapExpAmt = g.Key.EconCapExpAmt,
          };

Solution

  • Suppose that there are two corresponding entity classes named EconCode and FundCode, and the context variable is dbContext, The equivalent LINQ query to the SQL query provided would be:

    var query = from econ in dbContext.EconCode
                join fund in dbContext.FundCode on econ.FundCodeId equals fund.FundCodeId into joinedGroup
                from fund in joinedGroup.DefaultIfEmpty()
                group new { econ, fund } by new { econ.EconCodeId, econ.EconCodeName, econ.EconIncomeAmt, econ.EconRecExpAmt, econ.EconCapExpAmt, FundCodeId = (int?)fund.FundCodeId } into g
                select new {
                    g.Key.EconCodeId,
                    g.Key.EconCodeName,
                    g.Key.EconIncomeAmt,
                    g.Key.EconRecExpAmt,
                    g.Key.EconCapExpAmt,
                    FundCodeId = g.Key.FundCodeId ?? 0
                };