I've searched around and people talk about using ExpandDo with dynamic, but I haven't been able to figure it out how to do this with a collection returned from a LINQ query.
I'm doing an inner join on my database between 2 tables (student and enrollments)
var innerJoin =
from e in db.Enrollments
join s in db.Student on e.StudentID equals s.StudentID
select new { Student= s.Name , Course = e.CourseID };
I've tried
dynamic model = innerJoin.ToList().ToExpando();
return View(model)
and I have
@model System.Collections.Generic.IEnumerable<dynamic>
at the top of my View.cshtml
but that gives this error when I try navigating to the controller in the web application:
The model item passed into the dictionary is of type 'System.Dynamic.ExpandoObject', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[System.Object]'. ''
I also tried:
dynamic model = innerJoin.ToList();
return View(model);
but then in my view (.cshtml file) I
@foreach (dynamic item in Model)
{
<tr>
<td>
@Html.Raw(item.Course)
</td>
</tr>
}
it'll barf on the @Html.Raw line with
An exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in App_Web_index.cshtml.1bbec3a6.jtomobws.dll but was not handled in user code
Ideally I'd like to make it a one liner. In my view I'm hoping to be able to iterate over a collection of property bags, and extract the Student and Course fields. So my property bag would contain properties Student and Course, and they'd be a collection of them. I've looked at many similar posts, but none have done this
Thanks Thomas
EDITED
I assume that
innerJoin.ToList().ToExpando();
converts the list of your anonymous objects returned from the join into Expando object and not toIEnumerable<dynamic>
. If you want to get List of dynamic objects you can use something like:This will work for
System.Collections.Generic.IEnumerable<dynamic>
modelHere is the example for working fiddle
Although I really advise you to use strongly typed models. By using dynamic objects you basically giving up on most of the advantages of statically typed languages.