【问题标题】:Convert SQL to LINQ with IN and MAX使用 IN 和 MAX 将 SQL 转换为 LINQ
【发布时间】:2016-03-16 21:27:26
【问题描述】:

如何将下面的 SQL 语句转换为 LINQ?

select
    kcustnum,
    (custsnum + 1),
    custartype,
    kcustsrch 
from
    custmast 
where
    kcustnum = 'cn' 
    and
    custsnum in (
        select
            max(custsnum)
        from
            custmast
        where
            kcustnum = 'cn'
    )

【问题讨论】:

  • custmast 表的架构是什么?你能解释一下kcustnum和custsnum之间的区别吗?
  • 这个查询很可能在没有IN 子查询的情况下被重写。
  • 谢谢戴!你是对的,Teo 的语法成功了

标签: sql linq


【解决方案1】:

正如@Dai 所说,您不需要IN,因为您使用MAX。

你在找什么:

var res = _context.custmast
                 .Where(x => x.kcustnum == "cn" 
                          && x.custsnum == _context.custmast
                                   .Where(y => y.kcustnum == 'cn')
                                   .Max(y => y.custsnum))
                 .Select(x => new 
                             {
                                x.kcustnum,
                                (x.custsnum + 1),
                                x.custartype,
                                x.kcustsrch 
                             });

这是我的代码不起作用:

    public ActionResult NameSelect(string customerNumber)
    {
        var shipto = from n in db.cs_Custmast
                      .Where(x => x.kcustnum == customerNumber
                      && x.custsnum == db.cs_Custmast
                               .Where(y => y.kcustnum == customerNumber)
                               .Max(y => y.custsnum))
                      .Select (n => new CustomersViewModel
                         {
                            Account = n.kcustnum,
                            Suffix = (n.custsnum + 1),
                            AccountType = n.custartype,
                            Search = n.kcustsrch 
                         });


        return View("_NameSelection", shipto);
    }

【讨论】:

  • THX Teo!这行得通。我在没有 lamda 的情况下尝试过(因为他们把我搞糊涂了),却一无所获。
  • 看来我撒谎了。我仍然收到一条错误消息,提示“查询正文必须以 select 子句或 group 子句结尾”
猜你喜欢
  • 1970-01-01
  • 2020-01-21
  • 2012-06-30
  • 1970-01-01
  • 1970-01-01
  • 2015-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多