如果您正在执行Linq to Entity
,则不能在查询结束时使用ClassType
withnew
select
only anonymous types are allowed (new without type)
看一下我的项目的这个片段
//...
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
您new keyword
甚至在上添加了Select闭包,complex properties
您将收到此错误
所以查询中remove
的ClassTypes from new
关键字Linq to Entity
因为它将转换为sql语句并在SqlServer上执行
所以我什么时候可以用new with types
在select
封闭?
如果您正在处理,则可以使用它 LINQ to Object (in memory collection)
//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
在查询上执行后,它变得in memory collection
如此,我们可以new ClassTypes
在选择中使用