代码之家  ›  专栏  ›  技术社区  ›  Kjensen

LinqToSQL中的标量函数

  •  2
  • Kjensen  · 技术社区  · 15 年前

    在ado.net/sqlclient中,我经常这样做:

    SELECT COUNT(*) FROM SomeTable WHERE SomeKey = 1234

    …并使用executescalar返回count的值来启动它-以便简单检查是否存在某些内容。

    使用linqtosql我该怎么做?

    3 回复  |  直到 15 年前
        1
  •  6
  •   Daniel Brückner    15 年前
    if (context.SomeTable.Any(row => row.SomeKey == 1234))
    {
        DoStuff();
    }
    

    你也可以用 Count() .

    if (context.SomeTable.Count(row => row.SomeKey == 1234) > 0)
    {
        DoStuff();
    }
    

    但这需要在 Any() 可以在第一个匹配行之后返回-so 任意() 可能会有更好的性能。

        2
  •  3
  •   BFree    15 年前

    记住,linq to sql是延迟执行的,这意味着只有在访问集合时才实际执行查询。因此:

    var q = (from p in db.SomeTable
            where p.SomeKey == 1234
            select p).Count();
    

    将在SQL端转换为select count()。

        3
  •  2
  •   Mykroft    15 年前

    如果要查看是否存在某些内容,可以使用任意函数:

    if (context.SomeTable.Any(i => i.SomeKey == 1234))
    {
        return true;
    }
    

    或者,如果您真的想知道该计数,您可以使用Where函数和Count函数:

    context.SomeTable.Where(i=> i.SomeKey == 1234).Count();
    
    推荐文章