views:

689

answers:

2

Using dynamic linq (http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx) I run the query below which returns an IQueryable. On this result which is also an IEnumerable I am able to run a Count() however there is not ToList() to get the values. I can enumerate over them using a foreach but am not able to access the individual fields in the resultant anonymous type without reflection. Is this the only way? Thanks

var query =
                db.Customers.Where("City == @0 and Orders.Count >= @1", "London", 10).
                OrderBy("CompanyName").
                Select("New(CompanyName as Name, Phone)");

            foreach (var item in query)
            {
                foreach (var prop in item.GetType().GetProperties())
                {
                    Console.WriteLine(prop);
                }
            }

Tried casting but got an error Unable to cast object of type 'DynamicClass1' to type 'Test'.

 foreach (var item in query)
            {
                Console.WriteLine("{0}: {1}", ((Test)item).CompanyName, ((Test)item).Phone);
            }

public class Test {
            public string CompanyName { get; set; }
            public string Phone { get; set; }

}

A: 

If the IEnumerable is not generic then you ought to cast rather than use reflection.

Andrew Hare
A: 

You can't expect the type of you dynamic object to be resolved at compile time when your query is resolved at runtime. That's what dynamic linq is all about : it allows you to execute dynamic queries at the cost compile-time checking.

You have to use reflection to access properties of a dynamic type, at least until C# 4.

ybo