36

I'm working with MVC 4 and I have to update my database using Code First Migrations. What I'm trying to do is to select records from a database table, and insert them into a dropdown list where the user can select one.

I have an error that I don't understand:

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

Controller:

  public ActionResult Addnew()
        {
            var dba = new DefaultConnection();
            var query = dba.blob.Select(c => new SelectListItem
            {
                Value = c.id.ToString(),
                Text = c.name_company,
                Selected = c.id.Equals(3)
            });
            var model = new Companylist
            {
                xpto = query.AsEnumerable()
            };

            return View(model);
        }
2

4 Answers 4

67

You got this error because Entity Framework does not know how to execute .ToString() method in sql. So you should load the data by using ToList and then translate into SelectListItem as:

var query = dba.blob.ToList().Select(c => new SelectListItem
    {
    Value = c.id.ToString(),
    Text = c.name_company,
    Selected = c.id.Equals(3)
});

Edit: To make it more clear, Entity framework converts your use of query operators such as Select, Where ETC into an sql query to load the data. If you call a method like ToString(), which Entity Framework does not have an equivalent in sql, it will complain. SO the idea is to defer the use of such functions post data load. ToList, ToArray ETC force execution of the query thus loading of data. Once the data is loaded, any further operation (such as Select, Where ETC) is performed using Linq to Objects, on the data already in memory.

2
  • 54
    The main problem with this approach, what if you select from a table with thousands, or tens of thousands of records - ToList will pull them all down from the database into an object, which you then do yet another select on. Highly inefficient - better to use SqlFunctions: Value = SqlFunctions.StringConvert(c.id) Commented Oct 30, 2013 at 4:20
  • Amazing explanation both VarunK and NaytGrochowski
    – 3 rules
    Commented Sep 24, 2016 at 12:44
2

What if... you use:

Value = c.id + "",

instead of

Value = c.id.ToString(),

Edit

With this option, you are not retrieving all data from Database

0
0

just use delegate :

var query = dba.blob.Select(delegate(blob c)
{
    return new SelectListItem
        {
            Value = c.id.ToString(),
            Text = c.name_company,
            Selected = c.id.Equals(3)
        };
});
0

Following is how I do it to display as a SelectList.

 public List<BlobEntity> GetBlobs()
    {
        List<BlobEntity> blobs = null;
        using (var db = new MyDBEntities())
        {
            blobs = (from b in db.blobs
                     where b.id > 0 //Example filter
                     select new BlobEntity
                     {
                         ID = b.id,
                         CompanyName = b.name_company
                     }
                     ).ToList();

        }
        return blobs;
    }

   public static SelectList GetBlobsSelectList()
    {
        MyBL theBL = new MyBL();
        List<BlobEntity> blobEntites = theBL.GetBlobs();
        var listItems = blobEntites
             .Select(x => new SelectListItem { Text = x.CompanyName,
                                                Value = x.ID.ToString()
                                             })
             .ToList();
        SelectList blobsSelectList = new SelectList(listItems.AsEnumerable(), "Value", "Text");
        return blobsSelectList;
    }

   public class BlobEntity
   {
       public int ID { get; set; }
       public string CompanyName { get; set; }
   }

The current accepted answer (by @VarunK) is okay if you are selecting all records and all columns. However, if that is not the case, it is better to do a projection with required columns and records before applying ToList().

Take a look at Why LINQ to Entities does not recognize the method 'System.String ToString()?.

Other references: Problem with converting int to string in Linq to entities

Not the answer you're looking for? Browse other questions tagged or ask your own question.