Tuesday, August 30, 2016

LINQ to Entities does not recognize the method 'System.String ToString()

When working with Dropdownlists in ASP.NET MVC, I encountered an error as stated in the title of this post when casting an int variable through LINQ Select() statement.
List<SelectListItem> itemCountries = new List<SelectListItem>();
itemCountries.AddRange((from country in _context.CascadeCountries select country)
             .Select(x => new SelectListItem
     {                
      Value =  x.CountryID.ToString(), //error here...
      Text = x.CountryName                
     }).ToList());

After doing some research, I found out that the statement returned by the Select statement above is IQueryable and the itemCountries variable is an IEnumerable. So, the fix for this issue is to cast the LINQ statement with AsEnumerable() and then followed by the Select() statement which sets the values for the SelectListItems properties.
List<SelectListItem> itemCountries = new List<SelectListItem>();
itemCountries.AddRange((from country in _context.CascadeCountries select country)
             .AsEnumerable().Select(x => new SelectListItem
        {                
          Value =  x.CountryID.ToString(),
          Text = x.CountryName                
        }).ToList());

0 comments:

Post a Comment