如何将此SQL转换为ASP.NETMVC的LINQ?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (128)

我有一条SQL语句:

select 
    table1.DIRECTORATE_ID, 
    table2.PLA_NAME + '//' + table1.ENGLISH_DIRECTORATE_CODE as EngCode
from table1
inner join table2 on table1.PLA_ID = table2.PLA_ID order by EngCode

我需要在我的EF代码中执行相同类型的查询,它给我一个List<>。是这样的:

var query = (from t1 table1.DIRECTORATE_ID, table2.PLA_NAME + '//' + table1.ENGLISH_DIRECTORATE_CODE as EngCode
             from table1
             inner join table2 on table1.PLA_ID = table2.PLA_ID order by EngCode)
            .ToList();
提问于
用户回答回答于

您的from子句中有列引用。在SQL中,顺序是(在此示例中)

  1. select
  2. from
  3. join
  4. order by

在LINQ中,顺序是

  1. from
  2. join
  3. orderby
  4. select

您可以在查询语法中编写它:

var query = from t1 in table1
            join t2 in table2 on t1.PLA_ID equals t2.PLA_ID
            let EngCode = t2.PLA_NAME + "//" + t1.ENGLISH_DIRECTORATE_CODE
            orderby EngCode
            select new 
            { 
                t1.DIRECTORATE_ID, 
                EngCode
            }

var data = query.ToList();

或使用扩展方法

var data = table1
    .Join(
        table2,
        t1 => t1.PLA_ID,
        t2 => t2.PLA_ID,
        (t1, t2) => new 
        { 
            t1.DIRECTORATE_ID, 
            EngCode = t2.PLA_NAME + "//" + t1.ENGLISH_DIRECTORATE_CODE 
        })
    .OrderBy(x => x.EngCode)
    .ToList();

扫码关注云+社区

领取腾讯云代金券

年度创作总结 领取年终奖励