LINQ to Entities does not recognize the method ‘System.String ToString()’ method in MVC 4

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 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

Method 3

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

Method 4

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x