Alan Godfried
Alan Godfried

Reputation: 95

How can I Get the properties of T from IQueryable<T>?

I have a method that returns an IQueryable of T. Using Reflection I am getting the return type of the method which is the IQueryable of T. I would like to use Reflection to give me all of the properties of T, but when I use the following code, I get no properties:

        //Get return type of method and then get its Public properties
        var returnType = methodInfo.ReturnType; // returns typeof(IQueryable<T>)
        var returnTypePropertyInfos = returnType.GetProperties();
        var propertySpecs = returnTypePropertyInfos.Select(returnTypePropertyInfo => new VPropertySpec()
        {
            PropertyName = returnTypePropertyInfo.Name, PropertyType = returnTypePropertyInfo.PropertyType.Name
        }).ToList();

Upvotes: 1

Views: 1389

Answers (2)

flindeberg
flindeberg

Reputation: 5017

How I would have done it with LINQ:

var propertySpect = 
  from argument in methodInfo.ReturnType.GetGenericArguments()
  from property in argument.GetProperties()
  select new VPropertySpec() {
    PropertyName = property.Name, PropertyType = property.PropertyType.Name,
    // Maybe add for multiple generic arguments: GenericArgument = argument,
  };

Upvotes: 0

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

Assuming the type of property is IQueryable<T> you can do:

returnTypePropertyInfo.PropertyType.GetGenericArguments()[0].GetProperties();

Upvotes: 1

Related Questions