How to get the correct value of a dynamic type?

[update]

Sorry, I should mark this question as MVC-2, I pass the result of the request to view the model, so I have to indicate the type of my model in the View Defintion header. I declare the following:

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

as nothing has ever changed, and none of the answers work for me :(. finally, I used the ModelView class as a helper to include the result of my query 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 return the value in my view as follows:

 foreach(var item in result){ Category cat = item.Category; // throws exception 'object' does not contain a definition for 'Category' //... } 

Note that a query type like IQueryable is an anonymouse class ...

+4
source share
4 answers

Try explicitly declaring the names:

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

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

0
source

If you replace the inappropriate IQueryable<dynamic> declaration with var , make sure it works, I just tested it.

0
source

Your problem is that your foreach on the watch page is compiled into a separate assembly. Since anonymous types are internal, the speaker does not see this because permissions do not allow this.

The easiest fix is ​​to call ToList() in your request, and then select each anonymous type and copy the parameters to the declared class or expandoobject.

0
source

All Articles