How to count how many objects will be returned by an ObjectQuery<T>?

By : ADB

I am building an ObjectQuery like this:

        string query = "select value obj from Entities.Class as obj " +
                       "where obj.Property = @Value";

        ObjectQuery<Class> oQuery = new ObjectQuery<Class>(query, EntityContext.Instance);
        oQuery.Parameters.Add(new ObjectParameter("Value", someVariable));

I can now assign this object as a DataSource for a control, or iterate with a foreach loop or even force a materialization to a List, however, I can I count the number of objects that will be returned, without forcing a materialization?

Do I need to create a companion query that will execute a count() or is there a function that will do that for me somewhere?

Thank you.

By : ADB


If the count is lower than 1 then it has found a new record, if not, it already has that record.

By : kccer

The ObjectQuery<T> class implements the IEnumerable<T> interface, which supports the Count() method.

What do you get from this?

int count = oQuery.Count();
By : Jon Grant

ObjectQuery<T> implements IQueryable<T>, so can't you simply use the extension method:

int count = oQuery.Count();

What happens if you execute this? I would have expected the overall query to just do a Count()... (not that I've done much EF...).

This video can help you solving your question :)
By: admin