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
                      .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?


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

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

Need Your Help

DataGridViewComboBoxColumn Autosizes Incorrectly or Correctly-Only-on-Selection

winforms c#-4.0 datagridviewcolumn datagridviewcombobox

I have a DataGridViewComboBoxColumn object which serves as a datasource for one of the columns in my gridview.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.