开发者

How get propery value of an dynamic type?

[update]

I'm sorry, i should tag this question as MVC-2, I pass result of query into view's model, so i must specify type of my model in View's header defintion. I declare it like this:

Inherits="System.Web.Mvc.ViewPage<IQueryable<dynamic>>"

how ever nothing changed and none of answers doesn't work for me :(. finally i used an ModelView class as helpe开发者_开发百科r to put my query result in it. :(

[/update]

I have a query like this:

IQueryable<dynamic> result = from d in KiaNetRepository.KiaNetEntities.Discounts
             where d.AgentTypeID == agentTypeId
             select new { d.Category,  d.DiscountValue, d.PriceConfige };

then i retrive value in my view like this:

foreach(var item in result){

    Category cat = item.Category; // throws exception 'object' does not contain a definition for 'Category' 

    //...

}

note that type of query as IQueryable is anonymouse class...


Try to declare names explicitly:

select new { Category = d.Category,  DiscountValue = d.DiscountValue, PriceConfige = d.PriceConfige }


If you are not forcing result to be of IQueryeable<dynamic> for any specific reason, I would recommend using var result = .... This will let the compiler make result of type IQueryable<T> with T the type of the anonymous class that you create using new { ... } in the select. There is no necessity for using dynamic from the code that you show here.


If you replace the inappropriate declaration IQueryable<dynamic> by var, sure it works, I've just also tested it.


Your problem is that your foreach loop being in the view page gets compiled into a separate assembly. Since anonymous types are internal the dynamic doesn't see it because of the permissions don't allow it.

Simplest fix is to call ToList() on your query statement and then select each anonymous type and copy parameters to a declared class or expandoobject.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜