-1

I called a method that returns IQueryable. e.g var x = acDAL.GetData(); It returns 3 tables data by joining them. and I want to get data from this IQueryable for example

var x = acDAL.GetData(); 
foreach(var item in x) 
{ 
    int id=item.Id; 
}

How can I do this?

user2579758
  • 1
  • 1
  • 2

1 Answers1

2

You give the example:

var x = acDAL.GetData();
foreach(var a in x) {
    int id=a.Id;
}

But most if that will already work, especially since IQueryable implements IEnumerable. The problem is the .Id

You have two choices there:

  • know the T, and cast to IQueryable-of-T
  • use dynamic

The latter only involves changing the var in your example to dynamic:

var x = acDAL.GetData();
foreach(dynamic a in x) {
    int id=a.Id;
}

The former involves knowing the object - try a.GetType() to see what it is. Then:

var x = acDAL.GetData();
foreach(SomeType a in x) {
    int id=a.Id;
}

Or alternatively:

var x = (IQueryable<SomeType>)acDAL.GetData();
foreach(var a in x) {
    int id=a.Id;
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Thanks Marc for reply For you dynamic solution it gives me error of 'object' does not contain a definition for 'Id'. and a.GetType() is + a.GetType() {<>f__AnonymousTypeb3`23[System.Int32,System.Int32,System.Nullable`1[System.Decimal],System.Nullable`1[System.Int32],System.Nullable`1[System.Boolean],System.Nullable`1[System.Int32],System.Nullable`1[System.Int32],System.Nullable`1[System.Boolean],System.String,System.Nullable`1[System.Int32],} dynamic {System.RuntimeType} – user2579758 Jul 13 '13 at 19:22
  • @user the dynamic approach should work fine if it actually had an Id in the projection. Anonymous types are a pain to work with if exposed outside of their context. What does a.GetType().GetProperty("Id") return? Null? Or non-null? – Marc Gravell Jul 13 '13 at 20:14
  • a.GetType().GetProperty("Id") it returns {Int32 Id} – user2579758 Jul 14 '13 at 16:36