为什么LINQ to Entities无法识别方法'System.String ToString()?

Neo*_*Neo 30 linq asp.net-mvc entity-framework

在MVC3 Web应用程序中获取错误. LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.

当我尝试从查询中使用EF获取值时:

public class DataRepository
    {
        public mydataEntities1 dbContext = new mydataEntities1();

        public List<SelectListItem> GetPricingSecurityID()
        {
        var pricingSecurityID = (from m in dbContext.Reporting_DailyNAV_Pricing
                                     select new SelectListItem
                                         {
                                                Text = m.PricingSecurityID.ToString(),
                                                Value = m.PricingSecurityID.ToString()
                                         });

        return pricingSecurityID.ToList();
        }
    }
Run Code Online (Sandbox Code Playgroud)

Jay*_*Jay 54

那不能转换为SQL.我想,从理论上讲,它可以但不实施.

您只需在获得结果后执行投影:

var pricingSecurityID = (from m in dbContext.Reporting_DailyNAV_Pricing
                                     select m.PricingSecurityID).AsEnumerable()
    .Select(x => new SelectListItem{ Text = x.ToString(), Value = x.ToString() });
Run Code Online (Sandbox Code Playgroud)

  • 这里没有必要调用`ToList()` - 为什么要构建另一个列表,当`AsEnumerable`以较少的开销完成工作时? (6认同)
  • @MandeepJanjua:OP在最后调用`ToList`来返回一个列表 - 调用`ToList()没有意义.选择(...).ToList()`. (5认同)
  • @JonSkeet这取决于.如果您需要立即对结果进行操作,或者您希望等到实际编译器执行查询. (2认同)

Jon*_*eet 17

如果它已经是一个字符串,你为什么一开始要打电话ToString?我怀疑LINQ to Entities中没有包含翻译,因为它没有意义.将您的select子句更改为:

select new SelectListItem
{
    Text = m.PricingSecurityID,
    Value = m.PricingSecurityID
}
Run Code Online (Sandbox Code Playgroud)

如果您确实需要执行LINQ to Entities不支持的操作,请使用AsEnumerable从数据库查询转换到进程内:

public List<SelectListItem> GetPricingSecurityID()
{
    return dbContext.Reporting_DailyNAV_Pricing
                    .Select(m => m.PricingSecurityID)
                    .AsEnumerable() // Rest of query is local
                    // Add calls to ToString() if you really need them...
                    .Select(id => new SelectListItem { Text = id, Value = id })
                    .ToList();
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,我同意Jason的反对意见.你最好还是返回一个List<string>在其他地方渲染的东西.

还要注意,如果你只是要使用单个select子句或只是一个where子句,查询表达式确实不会增加太多 - 调用LINQ扩展方法最终可能会减少混乱,特别是如果你想调用的方法不是吨支撑在查询表达式(例如ToList).