错误-LINQ to Entities无法识别方法';System.StringToString(System.I

本文关键字:System StringToString 方法 to -LINQ Entities 识别 错误 | 更新日期: 2023-09-27 18:27:58

我正在将MVC3 linq转换为sql到MVC5实体框架6.1;我使用以下帮助下拉列表:

public static string ExDropDownList (this HtmlHelper helper, string name, IEnumerable<SelectListItem> selectList, bool readOnly, object htmlAttributes)
{
    string html = "";
    if (readOnly)
    {
        foreach (SelectListItem item in selectList)
        {
            if (item.Selected)
            {
                html = String.Format("<label for='{0}'>{1}</label>", name, item.Text);
                break;
                }
            }
        }
    else
        html = AddEmptyOption(System.Web.Mvc.Html.SelectExtensions.DropDownList(helper, name, selectList, htmlAttributes).ToString());
    return html;
}

我使用生成此列表

var proviences = lookupRepository.GetProviences();
IEnumerable<SelectListItem> selectListProvience =  from p in proviences
   select new SelectListItem
   {
      Text = p.ProvinceName,
      Value = p.ProvinceID.ToString(CultureInfo.InvariantCulture)
    };

我得到以下错误:

LINQ to Entities does not recognize the method 'System.String ToString(System.IFormatProvider)' method, and this method cannot be translated into a store expression

错误-LINQ to Entities无法识别方法';System.StringToString(System.I

在调用ToString()之前,需要实现查询。

var proviences = lookupRepository.GetProviences();
IEnumerable<SelectListItem> selectListProvience = (from p in proviences).AsEnumerable()
  .Select(p => new SelectListItem
  {
     Text = p.ProvinceName,
    ....

但它可能只是

var proviences = lookupRepository.GetProviences();
IEnumerable<SelectListItem> selectListProvience = proviences.Select(p => new SelectListItem
{
  Text = p.ProvinceName,

或者更简单的

SeelctList selectListProvience = new SelectList(proviences, "ProvinceID", "ProvinceName");

Entity Framework正试图将其转换为SQL,但由于无法处理ToString()而失败。尝试添加ToList()

var proviences = lookupRepository.GetProviences().ToList();

这会导致查询执行,但如果您选择了列表中的每一项,这也没问题。

我在分离模型项目时遇到了同样的问题我删除了using System.Data.Objects.SqlClient;,并将其替换为using System.Data.Entity.SqlServer;,问题消失了