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

问题描述 投票:0回答:1

我得到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; }
}
c# sql entity-framework linq enums
1个回答
3
投票

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

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

所以你不需要把它放在Select条款中。

© www.soinside.com 2019 - 2024. All rights reserved.