I have a base entity A, and derived entities: AA, AB, AC, AD
context.A.GroupBy(x => x.GetType()).Select(x => new { type=x.GetType(), count = x.Count() });
Of course I get error:
LINQ to Entities does not recognize the method 'System.Type GetType()' method, and this method cannot be translated into a store expression.
How can i group derived entities by type?
如果类型是预定义的,则可以使用Enumerable.OfType方法
var acs = context.A.OfType<AC>().Count();
You need to hydrate your entities to memory before calling the GroupBy - this way the x.GetType() call will be handled by LINQ to Objects and not LINQ to Entities. Try doing this:
context.A.ToList().GroupBy(x => x.GetType()).Select(x => new { type=x.Key, count = x.Count() });
I changed it so you call x.Key and not x.GetType() in your select, otherwise you will get the type of the grouping which will be something like IGrouping<...>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.