是否可以在 EntityFramework 中将 Select(l=> new{}) 与 SelectMany 一起使用
我正在尝试一些我不太确定的事情,但我想在这里问是否可能。
能做到吗?
public IQueryable<Info> 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);
}
当执行这个方法时我得到一个错误
实体或复杂类型 “GuideModel.Info”不能 在 LINQ to Entities 中构建 查询。
是“不可能”的意思吗?
谢谢
I am trying something that i not really sure but i want to ask here if it s possible.
Is it able to be done ?
public IQueryable<Info> 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);
}
When this method is executed i got an error
The entity or complex type
'GuideModel.Info' cannot be
constructed in a LINQ to Entities
query.
Does it mean "not possible" ?
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
该错误本质上表明实体框架不知道如何创建 Info 对象,因为它未绑定到表对象。 (换句话说,
IQueryable
上的Select
调用无法转换为等效的 SQL。)您可以通过以下方式在客户端上执行Select
投影: :The error essentially indicates that the Entity Framework doesn't know how to create an Info object, since it is not bound to a table object. (Put another way, the
Select
call on theIQueryable
cannot be translated into equivalent SQL.) You could perform theSelect
projection on the client via:可以使用
Select(l => new ...)
,但不能与实体类型一起使用。您需要使用匿名类型或带有无参数构造函数的 POCO 类型。实体类型因其与 ObjectContext 交互的方式而显得“特殊”。您可以选择它们,但不能在查询中新建它们。It is possible to use
Select(l => new ...)
, but not with an Entity type. You need to use an anonymous type or a POCO type with a parameterless constructor. Entity types are "special" because of the way they interact with the ObjectContext. You can select them, but not new them up in a query.下面的代码对我有用。这里的“SearchTerm”是一个复杂类型。谢谢杰森:)
The code below worked for me. Here "SearchTerm" is a complex type. Thanks Jason :)