【问题标题】:Count related entities without loading them, non-generic way计算相关实体而不加载它们,非通用方式
【发布时间】:2015-01-21 18:40:20
【问题描述】:

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 发生 HResult=-2146233067
消息=无法将类型“...”转换为类型 '系统.对象'。 LINQ to Entities 仅支持转换 EDM 原语 或枚举类型。来源=实体框架

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

【问题讨论】:

  • 对我来说,您必须使用反射来获得Expression<Func<TEntity, ICollection<TElement>>> 才能使用Collection 的通用版本,这将允许您使用Count()

标签: c# linq entity-framework generics entity-framework-6


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    你也可以写:

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

    这也不会加载对象。

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

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

    【讨论】:

    • 不知道是Blog还是别的什么。我已经编辑了问题,这有点误导
    • 您必须知道,因为在您的示例中,您假设您不那么未知的类型具有 Posts 属性。
    • @tschmit007 它是从 msdn 示例中复制粘贴的,现在已更正
    猜你喜欢
    • 2015-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-15
    • 2014-08-21
    • 1970-01-01
    相关资源
    最近更新 更多