(I've put "...to Entities" in brackets since I don't know if this matters at all. I guess this is a quite general LINQ related 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 am not wrong) this loads the full Client object from the database (if the Client exists). I am actually only interested whether it exists or not without loading the object.
SQL has the SELECT COUNT(*)... construct. Is there something similar I can do with LINQ?
Thank you for advice!
One option is to use the Any method of IQueryable. It will return a boolean value indicating whether or not an object was found matching the specified condition.
using (MyEntitiesContext aCtx = new MyEntitiesContext())
{
bool exists = (from c
in aCtx.Client
where c.ClientID==1
select c).Any();
}
This method will also stop running as soon as it evaluates to true.
I would then use Any() to determine existence. Regardless of whether you create a dummy instance like the following, the compiler will create a SQL statement using the Exists function and thus, it will not matter what is in the Select statement.
var query= from c
in context.Client
where c.ClientID == 1
select new { Dummy = "foo" };
var exists = query.Any();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With