使用IN和MAX将SQL转换为LINQ

时间:2016-03-16 21:27:27

标签: sql linq

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

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

1 个答案:

答案 0 :(得分:0)

由于@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);
    }