我在填充下拉列表时遇到问题。
使用以下代码填充IEnumerable
IEnumerable<SelectListItem> itemCollection = context.Countries.Select(item => new SelectListItem
{
Text = item.CountryName,
Value = item.CountryId
});
它在Value = item.CountryId
中给出了错误。无法将int类型隐式转换为字符串。
如果我将其更改为Value = Convert.ToString(item.CountryId)
,则会显示运行时错误
LINQ to Entities无法识别方法'System.String ToString(Int32)'方法,这个方法无法翻译成 商店表达。
据我所知,问题是Linq在执行时不允许转换语句。但是在我的数据库中,countrID是int无法更改的。
我知道有办法解决这个问题,但是我需要一些不会使代码变得混乱的具体内容?
答案 0 :(得分:0)
如果您调用AsEnumerable
扩展方法,您将获取数据并在内存中执行查询。否则,您的查询将被转换为动态SQL查询,由于SQL中ToString
没有任何等效表达式,因此您的RDBMS无法执行该查询。
IEnumerable<SelectListItem> itemCollection =
context.Countries
.AsEnumerable()
.Select(item => new SelectListItem
{
Text = item.CountryName,
Value = item.CountryId.ToString()
});