实体框架ORDER BY问题 [英] Entity Framework ORDER BY issue
问题描述
我正在尝试使用实体框架构建我的第一个MVC 4应用程序.我要寻找的就是创建一个下拉列表,将每个选项的值和文本设置为相同的值.
I'm attempting to build my first MVC 4 application using the entity framework. All I'm looking for is to create a drop down list with the value and text of each option set to the same value.
这有效,直到我扔出GroupBy()
.
Create.cshtml
Create.cshtml
@Html.DropDownList("CustomerName",(SelectList)ViewData["companies"]);
ticketController.cs
ticketController.cs
ViewBag.companies = new SelectList(oc_db.company.Where(c => c.status == "ACTIVE")
.OrderBy(c => c.name_1)
.GroupBy(c=>c.name_1)
, "name_1", "name_1");
这是我收到的错误:
数据绑定: 'System.Data.Objects.ELinq.InitializerMetadata + Grouping`2 [[System.String, mscorlib,版本= 4.0.0.0,文化=中性, PublicKeyToken = b77a5c561934e089],[OpsTicketing.Models.company, OpsTicketing,版本= 1.0.0.0,文化=中性,PublicKeyToken =空]]' 不包含名称为"name_1"的属性.
DataBinding: 'System.Data.Objects.ELinq.InitializerMetadata+Grouping`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[OpsTicketing.Models.company, OpsTicketing, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' does not contain a property with the name 'name_1'.
如果我不使用GroupBy
,则查询有效,尽管有重复.
If I don't use the GroupBy
the query works, albeit with duplicates.
推荐答案
GroupBy
不能为您提供基础类型的枚举.它为您提供IGrouping
对象的枚举,并带有一个Key
字段,该字段为您提供该组的键值,并提供一个IEnumerable
接口,该接口可以让您迭代该组的成员.
GroupBy
doesn't give you an enumeration of the underlying type. It gives you an enumeration of IGrouping
objects with a Key
field that gives you the key value for that group and an IEnumerable
interface that lets you iterate the members of that group.
如果您只想按顺序列出name_1
值的唯一列表,只需选择该字段并先执行Distinct
,然后再执行OrderBy
:
If all you want is a unique list of name_1
values in order, just select that field and do a Distinct
followed by an OrderBy
:
ViewBag.companies = new SelectList(oc_db.company.Where(c => c.status == "ACTIVE")
.Select(c=> new {c.name_1})
.Distinct()
.OrderBy(c => c.name_1)
, "name_1", "name_1");
请注意,您可以在没有.Select()
的情况下执行此操作,但是您必须为company
类定义平等",这比此练习的价值更大.这就是Distinct
以前无法工作的原因-因为您没有定义使两家公司脱颖而出的原因.
Note that you could do it without the .Select()
, but you'd have to define "equality" for your company
class, which is more trouble than it's worth for this exercise. That's why the Distinct
didn't work before - because you didn't define what makes two companies distinct.
这篇关于实体框架ORDER BY问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!