1

我正在使用反射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]'.
4

1 回答 1

2

这似乎是你应该能够做的事情,不是吗?但这是不允许的,这就是原因。

EntityCollection<T>是可写的,因此如果将 aEntityCollection<Derived>转换为 a EntityCollection<Base>,则可以将 Base 对象插入集合中。这意味着您现在拥有一个不是 Derived 且不是 Derived 的子类的实例EntityCollection<Derived>。然后怎样呢?期望 Derived的迭代器EntityCollection<Derived>将以各种令人兴奋的方式失败。

于 2012-07-17T17:45:43.520 回答