Donate

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());

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.