我如何修复" LINQ to Entities无法识别方法"错误

时间:2018-03-05 07:35:51

标签: c# sql entity-framework linq enums

我得到LINQ to Entities无法识别方法' System.String GetName(System.Type,System.Object)'方法,并且此方法无法转换为商店表达式。

我该如何解决?我没有找到适合我案例的例子。

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

型号:

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

1 个答案:

答案 0 :(得分:3)

最简单的方法可能是在ViewModel中使用简单的GenreName getter

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

所以你不需要把它放在Select子句中。