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.
Best Answer
GroupBy
doesn't give you an enumeration of the underlying type. It gives you an enumeration ofIGrouping
objects with aKey
field that gives you the key value for that group and anIEnumerable
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 aDistinct
followed by anOrderBy
:Note that you could do it without the
.Select()
, but you'd have to define "equality" for yourcompany
class, which is more trouble than it's worth for this exercise. That's why theDistinct
didn't work before - because you didn't define what makes two companies distinct.