我正在使用反射EntityCollection<Derived>
从我的 EF4 域实体中获取属性。一个示例实体可能有许多集合,这些集合包含具有共同基础的类型。GetValue()
返回 anobject
但我需要将其转换为 anEntityCollection<Base>
甚至只是IEnumerable<Base>
. 但是怎么做?(哎呀,从 C#4 开始,转换为 IEnumerable 确实有效)
示例模型
public class Derived : Base { ... }
public class AnotherDerived : Base { ... }
public class Example : Base
{
public virtual ICollection<Derived> Items { get; set; }
public virtual ICollection<AnotherDerived> OtherItems { get; set; }
}
我很难理解强制转换和多态性。我认为我能够通过DbSet<Derived>
将它们反射到IQueryable<Base>
. 但是EntityCollection
我无法将反射的对象恢复为可用的形式。
方法
public static List<T> GetCollectedEntities<T>(this BaseEntity entity)
where T : BaseEntity
{
var result = new List<T>();
foreach (var c in GetCollections<T>(entity))
foreach (var item in (EntityCollection<T>)c) //ERROR
result.Add(item);
return result;
}
public static List<object> GetCollections<T>(this BaseEntity entity)
where T : BaseEntity
{
var collections = new List<object>();
var props = from p in entity.GetType().GetProperties()
let t = p.PropertyType
where t.IsGenericType
&& t.GetGenericTypeDefinition() == typeof(ICollection<>)
let a = t.GetGenericArguments().Single()
where a == typeof(T) || a.IsSubclassOf(typeof(T))
select p;
foreach (var p in props)
collections.Add(p.GetValue(entity, null));
return collections;
}
现实世界的错误
Unable to cast object of type
'System.Data.Objects.DataClasses.EntityCollection`1[HTS.Data.ServiceOrder]'
to type
'System.Data.Objects.DataClasses.EntityCollection`1[HTS.Data.IncomingServiceOrderBase]'.