1

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.

artm
  • 8,554
  • 3
  • 26
  • 43
Evonet
  • 3,600
  • 4
  • 37
  • 83
  • 1
    possible duplicate of [Only initializers, entity members, and entity navigation properties are supported](http://stackoverflow.com/questions/6919709/only-initializers-entity-members-and-entity-navigation-properties-are-supporte) – Rahul Singh Nov 28 '14 at 11:52
  • The other example is fine if I wanted to add an additional predicate, but here I'm trying to get the last item of a list, and I'm unsure where to start – Evonet Nov 28 '14 at 11:55
  • The other example still applies. Change `p.LastComment` to `p.Comments.LastOrDefault()` and it should work. – DavidG Nov 28 '14 at 11:56
  • Changing to p.Comments.LastOrDefault() didn't work – Evonet Nov 28 '14 at 12:05

1 Answers1

2

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

Vsevolod Goloviznin
  • 12,074
  • 1
  • 49
  • 50