C# 使用 LINQ 创建 SelectListItem 的集合

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9812039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 10:43:03  来源:igfitidea点击:

Creating a collection of SelectListItem with LINQ

c#asp.netasp.net-mvc

提问by Steven

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 UserIDto a string:

尝试转换UserID为字符串时出现错误:

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

LINQ to Entities 无法识别方法“System.String ToString()”方法,并且此方法无法转换为存储表达式。

How I create a collection of SelectListItemfrom my entities?

我如何SelectListItem从我的实体创建一个集合?

采纳答案by Phil

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

ToString()只能在 Linq to Objects 中使用。一个简单的解决方案是插入.ToList()如下:

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.

这将从您的 User 表中返回所有用户。如果您可以减少从数据库中获取的用户数量,您的查询将更有效率,例如

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

回答by Sorax

I think you're looking for SqlFunctions

我想你正在寻找 SqlFunctions

using System.Data.Objects.SqlClient;

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

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