如果您正在执行 Linq to Entity
,则无法在查询的 select
闭包中使用带有 new
的 ClassType
,只允许使用匿名类型(不带类型的 new
)。
请看一下我的项目代码片段:
//...
var dbQuery = context.Set<Letter>()
.Include(letter => letter.LetterStatus)
.Select(l => new {Title =l.Title,ID = l.ID, LastModificationDate = l.LastModificationDate, DateCreated = l.DateCreated,LetterStatus = new {ID = l.LetterStatusID.Value,NameInArabic = l.LetterStatus.NameInArabic,NameInEnglish = l.LetterStatus.NameInEnglish} })
^^ without type__________________________________________________________________________________________________________^^ without type
如果您在Select闭包中添加了new关键字
,即使在复杂属性
上,您也会遇到此错误
所以,在Linq to Entity
查询中,删除new关键字的ClassTypes
因为它将被转换为SQL语句并在SqlServer上执行
那么什么情况下可以在select
闭包中使用new和types
?
如果您正在处理LINQ to Object(内存集合)
,则可以使用它
//opecations in tempList , LINQ to Entities; so we can not use class types in select only anonymous types are allowed
var tempList = dbQuery.Skip(10).Take(10).ToList();// this is list of <anonymous type> so we have to convert it so list of <letter>
//opecations in list , LINQ to Object; so we can use class types in select
list = tempList.Select(l => new Letter{ Title = l.Title, ID = l.ID, LastModificationDate = l.LastModificationDate, DateCreated = l.DateCreated, LetterStatus = new LetterStatus{ ID = l.LetterStatus.ID, NameInArabic = l.LetterStatus.NameInArabic, NameInEnglish = l.LetterStatus.NameInEnglish } }).ToList();
^^^^^^ with type
在查询上执行ToList
后,它变成了内存集合
,因此我们可以在选择中使用new ClassTypes