2

Let's say I have The class

public partial class MyEntities: DbContext { public DbSet<Customer> Customers {get;set;} public DbSet<CustomerInfo> CustomerInfos {get;set;} public DbSet<Order> Orders {get;set;} // etc } 

How can I find the property that has the generic type Customer?

In other words I am looking to create the method:

 public PropertyInfo GetProperty<T>(){ var allProperties = TypeOf(MyEntities).GetProperties(); // implementation } 

If I call the method as GetProperty<Customer>() then I will like to get the first property. If I call the method as GetProperty<Order>() then I will like to get the last property. How can I examine the <Type> with reflection?

1 Answer 1

7

Use Type.IsGenericType and Type.GetGenericArguments():

public PropertyInfo GetProperty<T>(){ var allProperties = TypeOf(MyEntities).GetProperties(); return allProperties.FirstOrDefault(prop => prop.PropertyType.IsGenericType && prop.PropertyType.GenericTypeArguments.FirstOrDefault() == typeof(T)); } 
Sign up to request clarification or add additional context in comments.

2 Comments

small change though I don't see the GenericTypeArguments property so I did prop.PropertyType.GetGenericArguments().FirstOrDefault()
@TonoNam oh, I guess "GenericTypeArguments" is new in .Net 4.5. I've updated.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.