astef
astef

Reputation: 9518

Count related entities without loading them, non-generic way

Here I learned how to count related entities without loading them. The problem is I have no entity type at compile-time. My case:

var postCount = context.Entry(someObject)   // someObject received from somewhere
                      .Collection(somePropertyString) 
                      .Query()              // and here I got a non-generic IQueryable
                      .Count();             // which has no Count method

If I'm trying to .Query().Cast<object>().Count() I'm getting run-time exception at this line:

System.NotSupportedException occurred HResult=-2146233067
Message=Unable to cast the type '...' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types. Source=EntityFramework

So, how to count related entities without loading them, if I has no entity type at compile-time?

Upvotes: 1

Views: 1565

Answers (2)

astef
astef

Reputation: 9518

Using reflection is an option. This extension method helped me:

public static int Count(this IQueryable q)
{
    return (int)q.Provider.Execute(
        Expression.Call(typeof(Queryable),
            "Count",
            new[] { q.ElementType },
            new[] { q.Expression }));
}

Upvotes: 1

Florian Schmidinger
Florian Schmidinger

Reputation: 4692

You can also write:

int count = context.Blogs.Single(blog=> blog.Id = yourCriteriaId).Posts.Count();

this would also not load the Object.

It would produce some SQL statement like this(simplified):

Select Count(*) from Post where Post.BlogID = 3

Upvotes: 1

Related Questions