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)
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
).
归档时间: |
|
查看次数: |
56109 次 |
最近记录: |