2012-07-17 84 views
1

我正在使用反射從我的EF4域實體獲取EntityCollection<Derived>屬性。一個示例實體可能擁有許多具有共同基礎的類型的集合。 GetValue()返回object,但我需要將其轉換爲EntityCollection<Base>或甚至只有IEnumerable<Base>。但是如何? (糟糕,澆鑄到IEnumerable的不工作爲C#4)無法將類型爲EntityCollection的對象<Derived>轉換爲EntityCollection <Base>

範例模型

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]'. 

回答

2

好像之類的事情,你應該能夠做到,不是嗎?但這是不允許的,這是爲什麼。

EntityCollection<T>是可寫的,因此如果您將EntityCollection<Derived>轉換爲EntityCollection<Base>,則可以將Base對象插入集合中。這意味着您現在有一個不是派生類的實例,並且不是派生於EntityCollection<Derived>中的子元素。然後怎樣呢?一個迭代器EntityCollection<Derived>,預計Derived將會以各種令人興奮的方式失敗。

+0

那麼鑄造成'IEnumerable '那麼呢? – Benjamin 2012-07-17 17:59:14

+0

大聲笑我以爲我已經嘗試過,並得到一個錯誤。有用。謝謝。 – Benjamin 2012-07-17 18:00:45

+0

如果您使用C#4,則可以進行IEnumerable 的協變分配。它不會在早期版本的.net中工作。請參閱http://msdn.microsoft.com/en-us/library/ee207183.aspx – MNGwinn 2012-07-17 18:01:54

相關問題