如何在 Child 的 属性 上制作 'group by' 并避免 'NotSupportedException'

How to make a 'group by' on a Child's property and avoiding a 'NotSupportedException'

我尝试按书籍类型获取外借数量。

我有这 3 个 class(简体)。 Code-first 模型的一部分:

 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();

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

Unable to cast the type 'Ips.Models.Book' to type 'Ips.Models.SmallBook'. LINQ to Entities only supports casting EDM primitive or enumeration types.

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

有点像..

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

您可以使用显式连接:

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();