Evonet
Evonet

Reputation: 3640

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.

Upvotes: 1

Views: 2507

Answers (1)

Vsevolod Goloviznin
Vsevolod Goloviznin

Reputation: 12324

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

Upvotes: 2

Related Questions