开发者

How do I get the data fields from an IQueryable variable?

I have the following code:-

public IQueryable GetPerson(int PersonID)
    {

        var Details = from pers in d开发者_Python百科b.People
              where pers.ID == PersonID
                      select new
                          {
                              Name = item.NAME,
                              Email = item.EMAIL
                          };

        return Details
    }

I don't want to return a specific Type from the data access code above.

Then I want to do something like:

 IQueryable Person = dal.GetPerson(PersonID);
 PersonEmail = Person.EMAIL;  - but this obviously doesn't work ??

Any ideas on how I can get the field data from the Person IQueryable object ?


In practice you cannot return an anonymous type from a method in any usefull way. You method will compile and work but you essentially have an IQueryable collection of objects and you cannot access the properties of the anonymous types contained in it. Unless you return IQueryable<Person> you simply cannot access the properties of the returned object, anonymous types are only really usefull within the scope they are created. There might be somethong horrible you could do with reflection to get the data out but i would not recomend going down that route. Why do you not want to return IQueryable<Person>?


I can think of 2 alternatives:

  • If your items have the same core properties named that you are going to be using then create an abstract class and have your method return a IQueryable item.
  • Return items in a dictionary instead of individually, that way you can access the names you want and their associated values.


The issue is that IQueryable is a collection: in this case IQueryable<[annonymous]> or something similar.

Try using IEnumerable as your return type instead and then do:

IEnumerable foundPerson = dal.GetPerson(personId);
string PersonEmail = foundPerson[0].Email;

Note: You may be able to do this with IQueryable as well: I've never tried, and I'm not looking at the documentation for the interface at the moment.

Correction: Since GetPerson() is its own method, you do lose your anonymous type and get just an Object back. The easy way to correct this is to use a named type (class or struct), though apparently there are some hacks (not recommended) that allow you to circumvent this.

Another option might be a Lambda expression which would pull back the data you need on a case-by-case basis, but then you'd probably have a fair deal of code repetition.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜