简体   繁体   中英

The specified type member is not supported in LINQ to Entities

I have a set of Stories and Comments and I'm trying to return a smaller DTO entity when being called by an API.

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."

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();
    }
}

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

           };
}

I expect that Linq can't convert my query to SQL, but I'm unsure of the correct approach to resolve this.

You can try the following code:

return (db.Stories.Include(x => x.Comments)).AsEnumerable().Select(p => 
           new StoryDTO()
           {
               StoryId = p.StoryId,
               LastComment = p.LastComment,
               NumberOfComments = p.Comments.Count

           };

This way you will be dealing with LINQ to Objects and EF will not try to convert all the stuff into SQL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM