【问题标题】:How to make a 'group by' on a Child's property and avoiding a 'NotSupportedException'如何在孩子的财产上进行“分组”并避免“NotSupportedException”
【发布时间】:2016-03-08 14:57:07
【问题描述】:

我尝试按图书类型获取贷款数量。

我有这 3 类(简体)。代码优先模型的一部分:

 public class Loan
   {
      public int LoanId {get;set;}
      .....
      public int BookId {get;set;}
      Public virtual Book {get;set;}

   }

    //Book parent class
    public class Book {
    public int BookId {get;set;}
    ...
    }

    //a Book child class with a specific 'Type' property
    public SmallBook : Book 
    {
     public string Type {get;set;} 
     ...
    }

这么久,我尝试了这种查询....

   var StatsMono = (from p in context.Loans
         //the 'where' clause allow to obtain all the loans where Loans.Book is a SmallBook.
         where context.Books.OfType<SmallBook>().Any(exm => exm.BookId == p.BookId)
         //here is my problem : i can't access 'SmallBook.Type' w/o cast
         group p by ((SmallBook)p.Book).Type into g
         select { GroupingElement=g.Key,intValue=g.Count()}
         ).ToList();

...但我无法摆脱以下异常:

无法将类型“Ips.Models.Book”转换为类型 'Ips.Models.SmallBook'。 LINQ to Entities 仅支持转换 EDM 原始类型或枚举类型。

我明白为什么会出现此错误,但现在我想知道是否有一种方法可以通过一个查询来实现我想要的?

【问题讨论】:

  • @AlperTungaArslan 我运行非多态查询以获取 SmallBooks 实体的方式。无论如何它不会改变任何东西,因为 exm 在这两种情况下都是 SmallBook 实体。

标签: c# linq linq-to-entities entity-framework-6


【解决方案1】:

您可以使用显式连接:

var StatsMono = (from p in db.Loans
                 join b in db.Books.OfType<SmallBook>() on p.BookId equals b.BookId
                 group p by b.Type into g
                 select new { GroupingElement = g.Key, intValue = g.Count() }
       ).ToList();

但最好将反向导航属性添加到您的模型中

public abstract class Book
{
    public int BookId { get; set; }
    // ...
    public ICollection<Loan> Loans { get; set; }
}

并使用它

var StatsMono = (from b in db.Books.OfType<SmallBook>()
                 from p in b.Loans
                 group p by b.Type into g
                 select new { GroupingElement = g.Key, intValue = g.Count() }
       ).ToList();

【讨论】:

  • 哎哟!我没想过要加入...它非常有效,谢谢!我会考虑使用反向导航属性,但我必须确保我不会得到 Json/Serialization 循环引用。
【解决方案2】:

有点像..

var result = context.Loans.GroupBy(g=> g.book.Type).select(s=> new { BookType= s.book.type, count = s.count }).ToList();

【讨论】:

  • 这行不通,因为 Book 中没有属性 'Type'。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-30
  • 1970-01-01
  • 1970-01-01
  • 2012-11-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多