0

I got LINQ to Entities does not recognize the method 'System.String GetName(System.Type, System.Object)' method, and this method cannot be translated into a store expression.

How can i fix that? I did not find a suitable example for my case.

 return context.Books.Select(e => new BookViewModel
            {
                BookId = e.BookId,
                BookName = e.BookName,
                Genre = new GenreViewModel
                { GenreName = Enum.GetName(typeof(Genre), (int)e.Genre), GenreId = (int)e.Genre },// error is here
                Pages = e.Pages,
                Publisher = e.Publisher,
                Authors = e.Authors.Select(t => new AuthorViewModel
                {
                    AuthorId = t.AuthorId,
                    AuthorName = t.AuthorName
                }).ToList()
            });

Models:

public enum Genre
{
[Description("Comedy")]
Comedy,
[Description("Drama")]
Drama,
[Description("Horror")]
Horror,
[Description("Realism")]
Realism,
[Description("Romance")]
Romance,
[Description("Satire")]
Satire,
[Description("Tragedy")]
Tragedy,
[Description("Tragicomedy")]
Tragicomedy,
[Description("Fantasy")]
Fantasy,
[Description("Mythology")]
Mythology,
[Description("Adventure")]
Adventure,
}
public class GenreViewModel
{
        public int GenreId { get; set; }
        public string GenreName { get; set; }
}
Vlad
  • 193
  • 2
  • 14

1 Answers1

4

The easiest way is probably to use a simple getter for GenreName in your ViewModel

public class GenreViewModel
{
        public int GenreId { get; set; }
        public string GenreName { get{ return Enum.GetName(typeof(Genre), GenreId);}}
}

So you don't need to put this in the Select clause.

Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122