【发布时间】: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