This is my controller's code:
IQueryable<Foo> foos = dbContext.Foos.Where(...);
return View(foos);
And this razor code (cshtml) works well:
@model IQueryable<Foo>
@{
IQueryable<Foo> foos = Model;
var projected = foos.Select(e => new
{
fooId = e.FooId,
bar = new
{
barId = e.Foo.BarId
}
}).ToList();
}
@foreach (var x in projected)
{
<span>@x.fooId</span><br />
}
But this razor code (cshtml) doesn't work, being almost the same thing!:
@model IQueryable<Foo>
@{
IQueryable<Foo> foos = Model;
var projected = foos.Selected(Foo.Projection()).ToList()
}
@foreach (var x in projected)
{
<span>@x.fooId</span><br />
}
Foo.Projection()
is a static method that I reuse a lot:
public static Expression<Func<Foo, dynamic>> Projection()
{
return e => new
{
fooId = e.FooId,
bar = new
{
barId = e.Foo.BarId
}
}
}
I'm getting that famous error: 'object' does not contain definition for 'fooId'
, which is discussed in here: MVC Razor dynamic model, 'object' does not contain definition for 'PropertyName' -but none of those answers helped me.
The accepted answer says: "now that MVC 3 has direct support for dynamic, the technique below is no longer necessary", so I also tried to return the projected List<dynamic>
to the view ("ready to use, no projection needed") and it didn't work either (getting the same error). This is the code for that attempt:
Controller's code:
List<dynamic> foos = dbContext.Foos.Select(Foo.Projection()).ToList();
return View(foos);
View's code:
@model dynamic
etc.
Edit: With the debugger I'm able to check (just after the exception is thrown) that the item indeed has "a definition for..."
(in the example code the item is x
, but here is lot
)