LINQ to Entities不支持指定的类型成员 [英] The specified type member is not supported in LINQ to Entities
问题描述
我有一组故事和评论,我试图在API被调用时返回一个较小的DTO实体。
I have a set of Stories and Comments and I'm trying to return a smaller DTO entity when being called by an API.
我正在尝试检索只是最后一个注释,但是得到错误LINQ to Entities不支持指定的类型成员LastComment,只支持初始化,实体成员和实体导航属性。
I'm trying to retrieve just the last comment but getting the error that "The specified type member 'LastComment' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported."
我的Story.cs:
My Story.cs:
public Story()
{
Comments = new List<Comment>();
}
public int StoryId { get; set; }
public List<Comment> Comments { get; set; }
public Comment LastComment
{
get
{
return Comments.LastOrDefault();
}
}
我的API GET方法:
And my API GET method:
public IEnumerable<StoryDTO> Get()
{
return from p in db.Stories
.Include(x => x.Comments)
select new StoryDTO()
{
StoryId = p.StoryId,
LastComment = p.LastComment,
NumberOfComments = p.Comments.Count
};
}
我希望Linq不能将我的查询转换为SQL,
I expect that Linq can't convert my query to SQL, but I'm unsure of the correct approach to resolve this.
推荐答案
您可以尝试以下代码:
return (db.Stories.Include(x => x.Comments)).AsEnumerable().Select(p =>
new StoryDTO()
{
StoryId = p.StoryId,
LastComment = p.LastComment,
NumberOfComments = p.Comments.Count
};
这样你将处理LINQ to Objects和EF不会尝试将所有的东西转换成SQL
This way you will be dealing with LINQ to Objects and EF will not try to convert all the stuff into SQL
这篇关于LINQ to Entities不支持指定的类型成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!