如果你正在执行实体的Linq,你不能在查询的选择闭包中使用带有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
如果你在选择闭包中添加了new关键字,即使在复杂的属性上,你也会得到这个错误
因此,从Linq上的new关键字删除类类型到实体查询,
因为它将转换为sql语句并在SqlServer上执行
什么时候我可以使用new with types on select closure?
如果你在处理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后,它变成了内存集合,所以我们可以在选择中使用新的classttypes