Entity Framework ORDER BY issue

青春壹個敷衍的年華 提交于 2019-12-23 13:15:35

问题


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.

This works, right up until I throw in the GroupBy().

Create.cshtml

@Html.DropDownList("CustomerName",(SelectList)ViewData["companies"]);

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

Here is the Error I'm receiving:

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'.

If I don't use the GroupBy the query works, albeit with duplicates.


回答1:


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.

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

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.




回答2:


You'll have to resolve the query before performing the GroupBy, which you can do by calling .ToList()




回答3:


How about using .Distinct()? http://msdn.microsoft.com/en-us/library/bb348436.aspx

Should work if this is all you need.




回答4:


Are you using the grouping just to make the list distinct? If so, try:

.Where(c => c.status == "ACTIVE")
.OrderBy(c => c.name_1)
.Distinct()


来源:https://stackoverflow.com/questions/14593426/entity-framework-order-by-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!