是否可以在EntityFramework中对SelectMany使用Select(l => new {})

我正在尝试一些我不太确定的事情,但我想在这里询问是否有可能。

能够做到吗?

public IQueryable GetInfo(int count, byte languageId) { return db.Info.SelectMany(i => i.LanguageInfo) .Where(l => l.Language.id == languageId) .Select(l => new Info { AddDate = l.Info.AddDate, Description = l.Description, EntityKey = l.Info.EntityKey, id = l.Info.id, Title = l.Title, ViewCount = l.Info.ViewCount } ) .OrderByDescending(i => i.id) .Take(count); } 

执行此方法时出现错误

无法在LINQ to Entities查询中构造实体或复杂类型“GuideModel.Info”。

这是否意味着“不可能”?

谢谢

该错误实质上表明entity framework不知道如何创建Info对象,因为它没有绑定到表对象。 (换句话说, IQueryable上的Select调用无法转换为等效的SQL。)您可以通过以下方式在客户端上执行Select投影:

 public IQueryable GetInfo(int count, byte languageId) { return db.Info.SelectMany(i => i.LanguageInfo) .Where(l => l.Language.id == languageId) .Take(count) .AsEnumerable() .Select(l => new Info { AddDate = l.Info.AddDate, Description = l.Description, EntityKey = l.Info.EntityKey, id = l.Info.id, Title = l.Title, ViewCount = l.Info.ViewCount } ) .OrderByDescending(i => i.id); } 

可以使用Select(l => new ...) ,但不能使用Entity类型。 您需要使用匿名类型或POCO类型与无参数构造函数。 实体类型是“特殊的”,因为它们与ObjectContext交互的方式。 您可以选择它们,但不能在查询中新建它们。

下面的代码对我有用。 这里“SearchTerm”是一个复杂的类型。 谢谢贾森:)

 var lstSynonym = TechContext.TermSynonyms .Where(p => p.Name.StartsWith(startLetter)) .AsEnumerable() .Select(u => new SearchTerm { ContentId = u.ContentId, Title = u.Name, Url = u.Url });