How can I get the name of an ICollection<> property from a reference to the contained type?
I have type references A
and B
but I want the name of the ICollection<A>
which is a property of B
. How can I get the collection name "BunchOfX" if I only have the two types?
public class X
{
}
public class Y
{
public virtual ICollection<X> BunchOfX { get; set; }
}
I need something that can give me the property name "BunchOfX" when all I have is the type references A and B. Let's say A will reference the type that the ICollection<> holds, and B will reference the type the ICollection<> is defined on.
The Real Code
var entityType = Type.GetType(nameSpace + "." + entityTypeName);开发者_如何学Go
var foreignType = Type.GetType(nameSpace + "." + foreignTypeName);
var names = foreignType.GetProperties()
.Where(p => typeof(ICollection<entityType>).IsAssignableFrom(p.PropertyType))
.Select(p => p.Name);
var foreignCollectionName = names.FirstOrDefault();
entityType gives "type or namespace unknown"
when it is in the <>
Solution based on Jon and Ani's replies
var foreignCollectionName = foreignType.GetProperties()
.Where(p => typeof(ICollection<>)
.MakeGenericType(entityType)
.IsAssignableFrom(p.PropertyType))
.Select(p => p.Name).FirstOrDefault();
You'd need to look through the properties with reflection. The easiest way to do this is using LINQ:
var names = typeOfB.GetProperties()
.Where(p => p.PropertyType == typeof(desiredPropertyType))
.Select(p => p.Name);
精彩评论