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

使用LINQ查询对象是否存在(到实体)

  •  3
  • Slauma  · 技术社区  · 15 年前

    (我把“…实体”放在括号里,因为我不知道这是否重要。我想这是一个相当普遍的与LINQ相关的问题。)

    我想用LINQ(to Entities)检查数据库中是否存在对象。目前我正在做以下工作:

    using (MyEntitiesContext aCtx = new MyEntitiesContext())
    {
        var aQuery = from c
                     in aCtx.Client
                     where c.ClientID==1
                     select c;
    
        Client aClient = aQuery.FirstOrDefault();
    
        bool Exists = (aClient!=null);
        ...
    }
    

    SQL具有 SELECT COUNT(*)... 构造。我能用LINQ做些类似的事情吗?

    4 回复  |  直到 15 年前
        1
  •  7
  •   PatrickJ    15 年前

    Any 液化方法。它将返回一个布尔值,指示是否找到与指定条件匹配的对象。

    using (MyEntitiesContext aCtx = new MyEntitiesContext())
    {
        bool exists = (from c
                       in aCtx.Client
                       where c.ClientID==1
                       select c).Any();
    }
    

    此方法在计算结果为true时也将停止运行。

        2
  •  2
  •   Thomas    15 年前

    我会用 Any() 确定存在。不管是否创建如下所示的伪实例,编译器都将使用Exists函数创建SQL语句,因此,Select语句中的内容无关紧要。

    var query= from c
                in context.Client
                where c.ClientID == 1
                select new { Dummy = "foo" };
    
    var exists = query.Any();
    
        3
  •  0
  •   TGnat    15 年前

    你可以试试。。。

    using (MyEntitiesContext aCtx = new MyEntitiesContext())
    {
         var aQuery = from c
             in aCtx.Client
             where c.ClientID==1
             select c;
    
         int total = aQuery.Count();
    
         bool Exists = (total > 0);
         ...
    }
    

        4
  •  0
  •   Johannes Rudolph    15 年前

    您可以在查询中使用Count()运算符或Any运算符来检查它是否会返回结果:

    using (MyEntitiesContext aCtx = new MyEntitiesContext())
    {
        var aQuery = from c
                     in aCtx.Client
                     where c.ClientID==1
                     select c;
    
        int count = aQuery.Count();
    
        bool Exists = (count > 0);
    
        // or
        Exists = aQuery.Any();
    
        ...
    }