Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get List if Properties of type ICollection from Generic Class

I have an object that contains some ICollection type properties

So basically the class looks like this:

Class Employee {

public ICollection<Address> Addresses {get;set;}

public ICollection<Performance> Performances {get; set;}

}

The problem is get property names of type ICollection, inside of Generic class, by using reflection.

My Generic Class is

Class CRUD<TEntity>  {

public object Get() {
 var properties = typeof(TEntity).GetProperties().Where(m=m.GetType() == typeof(ICollection ) ... 
}

But it is not working.

How can I get a property here?

like image 961
codebased Avatar asked Dec 26 '22 06:12

codebased


1 Answers

GetProperties() returns a PropertyInfo[]. You then do a Where using m.GetType(). If we assume that you missed a >, and this is m=>m.GetType(), then you are actually saying:

 typeof(PropertyInfo) == typeof(ICollection)

(caveat: actually, it is probably a RuntimePropertyInfo, etc)

What you mean is probably:

typeof(ICollection).IsAssignableFrom(m.PropertyType)

However! Note that ICollection <> ICollection<> <> ICollection<Address> etc - so it isn't even that easy. You might need:

m.PropertyType.IsGenericType &&
    m.PropertyType.GetGenericTypeDefinition() == typeof(ICollection<>)

Confirmed; this works:

static void Main()
{
    Foo<Employee>();
}
static void Foo<TEntity>() {
    var properties = typeof(TEntity).GetProperties().Where(m =>
        m.PropertyType.IsGenericType &&
        m.PropertyType.GetGenericTypeDefinition() == typeof(ICollection<>)
    ).ToArray();
    // ^^^ contains Addresses and Performances
}
like image 162
Marc Gravell Avatar answered Feb 13 '23 22:02

Marc Gravell