Entity Framework ORDER BY issue

c# entity-framework exception-handling linq sql-order-by

Question

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
4
1/30/2013 12:23:52 AM

Accepted Answer

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.

5
1/30/2013 4:01:06 AM

Popular Answer

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



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow