0

I am facing issues while populating dropdownlist.

Using below code to populate IEnumerable

IEnumerable<SelectListItem> itemCollection = context.Countries.Select(item => new SelectListItem
{
       Text = item.CountryName,
       Value = item.CountryId
});

it gives error in Value = item.CountryId Cannot implicitly convert type int to string.

if I changes this to Value = Convert.ToString(item.CountryId) it give run time error

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

I understand that the problem is Linq does not allow convert statement while executing. But the countrID is int in my database cannot be changed.

I know there are options to workaround this, but i need something concrete that will not make code messy?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
ankur
  • 4,565
  • 14
  • 64
  • 100
  • 1
    Possible duplicate of [LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression](http://stackoverflow.com/questions/5899683/linq-to-entities-does-not-recognize-the-method-system-string-tostring-method) – Rahul Singh Dec 10 '15 at 07:09
  • 1
    Materialize you query - `.... context.Countries.ToList().Select(...` and then `item.CountryId.ToString()` –  Dec 10 '15 at 07:10

1 Answers1

0

If you call the AsEnumerable extension method, you will get your data and execute your query in memory. Otherwise, your query would be transalated to a dynamic sql query, which coulnd't be executed by your RDBMS due to the fact that there isn't any equivalent expression for ToString in SQL.

IEnumerable<SelectListItem> itemCollection = 
   context.Countries
          .AsEnumerable()
          .Select(item => new SelectListItem
          {
              Text = item.CountryName,
              Value = item.CountryId.ToString()
          });
Christos
  • 53,228
  • 8
  • 76
  • 108