LINQ to Entities无法识别该方法,并且此方法无法转换为存储表达式

Kis*_*mar 6 .net c# wpf entity-framework linq-to-sql

var ps = dbContext.SplLedgers.Select(p => new SplLedgerModel
            {
                Name = p.Name,
                VoucherType = Convert.ToString(((JIMS.VoucherTypes)p.VoucherType))
        });
Run Code Online (Sandbox Code Playgroud)

我得到以下异常,代码有什么问题.

JIMS.VoucherType是一个枚举

+       $exception  {"LINQ to Entities does not recognize the method 'System.String ToString(System.Object)' method, and this method cannot be translated into a store expression."}    System.Exception {System.NotSupportedException}
Run Code Online (Sandbox Code Playgroud)

Jus*_*vey 8

你的代码基本上是试图在DB中找到Convert.ToString()方法,可以理解为失败.

你可以绕过它,例如通过确保查询在select之前执行,例如

var ps = dbContext.SplLedgers.Select(p => new  
    { 
         Name = p.Name, 
         VoucherType = p.VoucherType
    }).ToList().Select(p => new SplLedgerModel( 
    { 
         Name = p.Name, 
         VoucherType = Convert.ToString(((JIMS.VoucherTypes)p.VoucherType)) 
    }); 
Run Code Online (Sandbox Code Playgroud)

  • 缺点是检索SplLedgers的所有列,而不是仅检索Name和VoucherType(可能是或不是重要的)。 (2认同)