我正在使用反射從我的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]'.
那麼鑄造成'IEnumerable '那麼呢? –
Benjamin
2012-07-17 17:59:14
大聲笑我以爲我已經嘗試過,並得到一個錯誤。有用。謝謝。 – Benjamin 2012-07-17 18:00:45
如果您使用C#4,則可以進行IEnumerable的協變分配。它不會在早期版本的.net中工作。請參閱http://msdn.microsoft.com/en-us/library/ee207183.aspx –
MNGwinn
2012-07-17 18:01:54