计算相关实体而不加载它们,非通用方式

Count related entities without loading them, non-generic way

Here 我学会了如何计算相关实体而不加载它们。问题是我在编译时没有实体类型。我的情况:

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

如果我尝试 .Query().Cast<object>().Count(),我会在这一行收到 运行 次异常:

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

那么,如果我在编译时没有实体类型,如何计算相关实体而不加载它们?

你也可以这样写:

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

这也不会加载对象。

它会产生一些像这样的SQL语句(简化):

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

使用反射是一种选择。这个扩展方法帮助了我:

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