[英]Count related entities without loading them, non-generic way
在这里,我学习了如何计算相关实体而不加载它们。 问题是我在编译时没有实体类型。 我的情况:
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
Message =无法将类型'...'强制转换为类型'System.Object'。 LINQ to Entities仅支持强制转换EDM基本类型或枚举类型。 来源=的EntityFramework
那么,如果我在编译时没有实体类型,该如何计算相关实体而不加载它们呢?
使用反射是一种选择。 这种扩展方法帮助我:
public static int Count(this IQueryable q)
{
return (int)q.Provider.Execute(
Expression.Call(typeof(Queryable),
"Count",
new[] { q.ElementType },
new[] { q.Expression }));
}
您还可以编写:
int count = context.Blogs.Single(blog=> blog.Id = yourCriteriaId).Posts.Count();
这也不会加载对象。
它将产生一些像这样(简化)的SQL语句:
Select Count(*) from Post where Post.BlogID = 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.