ORITLE Framework problem
I am trying to create my first MVC 4 application using entity framework. All I'm looking for is to create a dropdown with the value and text of each option set to one value.
This works until I close 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 am getting:
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 named' name_1 '.
If I don't use the GroupBy
query works, albeit with duplicates.
source to share
GroupBy
doesn't give you an enumeration of the base type. It gives you an enumeration of objects IGrouping
with a field Key
that gives you the key value for that group and an interface IEnumerable
that lets you iterate over the members of that group.
If all you want is a unique list of values name_1
in order, just select that field and do Distinct
, and then 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 can do this without .Select()
, but you will need to define "equality" for your class company
, which is more of a problem than it is worth for this exercise. This is why it has Distinct
n't worked before - because you haven't defined what separates the two companies.
source to share
How about using .Distinct ()? http://msdn.microsoft.com/en-us/library/bb348436.aspx
Should work if that's all you need.
source to share