【问题标题】:How can i fix "LINQ to Entities does not recognize the method" error如何修复“LINQ to Entities 无法识别该方法”错误
【发布时间】:2018-03-05 07:35:51
【问题描述】:

我得到的 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】:

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

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

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

【讨论】:

  • 非常感谢,这真的是一个非常简单有效的解决方案)
猜你喜欢
  • 2013-06-04
  • 1970-01-01
  • 2021-11-06
相关资源
最近更新 更多