Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a collection of SelectListItem with LINQ

Tags:

I'm trying to display a dropdown list of users in my view. Here is the code I'm using in my controller method:

var users = _usersRepository.Users.Select(u => new SelectListItem
                                    {
                                        Text = u.FirstName + " " + u.LastName,
                                        Value = u.UserID.ToString()
                                    }

return View(new MyViewModel { Users = users });

I get an error trying to convert UserID to a string:

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

How I create a collection of SelectListItem from my entities?

like image 565
Steven Avatar asked Mar 21 '12 20:03

Steven


People also ask

What collections can LINQ be used with?

You can use LINQ to query any enumerable collections such as List<T>, Array, or Dictionary<TKey,TValue>. The collection may be user-defined or may be returned by a . NET API.

Can we apply LINQ on Array?

Yes it supports General Arrays, Generic Lists, XML, Databases and even flat files. The beauty of LINQ is uniformity.

How many types of LINQ are there?

There are two syntaxes of LINQ.


1 Answers

ToString() can only be used in Linq to Objects. A simple solution is to insert .ToList() as follows:

var users = _usersRepository.Users.ToList().Select(u => new SelectListItem
                                    {
                                        Text = u.FirstName + " " + u.LastName,
                                        Value = u.UserID.ToString()
                                    });

return View(new MyViewModel { Users = users });

This is going to return all users from your User table. If you can reduce the amount of users obtained from the database your query will be more efficient, e.g.

var users = _usersRepository.Users.Where( u => .... ).ToList().Select(u => new SelectListItem
                                    {
                                        Text = u.FirstName + " " + u.LastName,
                                        Value = u.UserID.ToString()
                                    });

return View(new MyViewModel { Users = users });
like image 133
Phil Avatar answered Oct 04 '22 15:10

Phil