如何对孩子的财产进行'group by'并避免"不支持异常"



我尝试按书籍类型获取贷款计数。

我有这 3 类(简化).part的代码优先模型:

 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 实体仅支持强制转换 EDM 基元或枚举类型。

明白为什么我会收到此错误,但现在我想知道是否有办法仅通过一个查询来实现我想要的?

您可以使用显式连接:

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

类似的东西..

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

相关内容

最新更新