简体   繁体   English

EntityFramework GroupBy实体类型

[英]EntityFramework GroupBy Entity Type

I have a base entity A, and derived entities: AA, AB, AC, AD 我有一个基本实体A,以及一个衍生实体: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. LINQ to Entities无法识别方法'System.Type GetType()',并且该方法无法转换为商店表达式。

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. 您需要在调用GroupBy之前将您的实体存储到内存中-通过这种方式,LINQ to Objects(而不是LINQ to Entities)将处理x.GetType()调用。 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<...> 我更改了它,因此您在选择中调用了x.Key而不是x.GetType(),否则您将获得分组的类型,类似于IGrouping <...>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM