An object existence query with LINQ (for entities)

(I put "... essentially" in brackets, because I don’t know if this matters at all. I think this is a pretty general LINQ question.)

I want to check with LINQ (to Entities) if an object exists in the database. At the moment, I am doing the following:

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);
    ...
}

But (if I'm not mistaken), it loads the entire Client object from the database (if the Client exists). I'm really curious if this exists or not without loading the object.

SQL has a construct SELECT COUNT(*).... Is there something similar that I can do with LINQ?

Thanks for the advice!

+3
source share
4 answers

Any IQueryable. , , , .

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

, true.

+7

Any() . , , , SQL Exists , , , Select.

var query= from c
            in context.Client
            where c.ClientID == 1
            select new { Dummy = "foo" };

var exists = query.Any();
+2

You can try...

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);
     ...
}

Unconfirmed...

0
source

You can use the Count () operator or Any Operator in your query to check if it will return the result:

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();

    ...
}
0
source

Source: https://habr.com/ru/post/1743512/


All Articles