Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Entity Framework ORDER BY issue

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().




ViewBag.companies = new SelectList(oc_db.company.Where(c => c.status == "ACTIVE")
                                                 .OrderBy(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=, Culture=neutral, PublicKeyToken=b77a5c561934e089],[OpsTicketing.Models.company, OpsTicketing, Version=, 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.

like image 868
Dakine83 Avatar asked Feb 17 '23 16:02


1 Answers

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

like image 167
D Stanley Avatar answered Feb 20 '23 09:02

D Stanley