[英]How to iterate through an ICollection type property with reflection
標題僅涵蓋了我要實現的目標中很小的一部分,因此請提前告知。 我正在嘗試建立一種在實體本身更新時正確更新其集合屬性的通用方法。 簡而言之,我想做一些與這里說明的方法類似的事情,但我想采用通用的方法。 為此,我創建了一個名為EntityCollectionPropertyAttribute
的屬性,並標記了我也需要更新的實體的那些屬性。 這是一個例子:
public class Teacher{
public int TeacherId{get;set;}
public string Name{get;set;}
}
public class Student{
public int StudentId{get;set;}
public string Name {get;set;}
[EntityCollectionProperty]
public virtual ICollection<Teacher> Teachers{get;set;}
}
public bool IsPropertyAnEntityCollection(PropertyInfo prop){
return Attribute.IsDefined(prop, typeof(EntityCollectionPropertyAttribute));
}
public void Update<T>(T entity)where T:class{
DbEntityEntry entry = MyDbContext.Entry(entity);
foreach (var prop in entry.Entity.GetType().GetProperties())
{
if(IsPropertyAnEntityCollection(prop)){
//Here's where I get stuck
}
}
}
假設已更新的父實體是學生。 除了名稱(可能還有ID)屬性外,我還需要更新教師。 因此,在評論區域中,我需要這樣的東西:
var updatedTeachers=studentEntity.Teachers.ToList();
但當然是通用方式。 我還必須單獨在DbContext內部查找教師DBSet。 所以我也需要這樣的東西:
var exisitingTeachers=MyDbContext.Teachers.ToList();
任何想法如何做到這一點?
您可以通過在此方法中傳遞屬性值prop.GetValue(entity)
來調用ToList
方法:
private IList CollectionToList(object value)
{
var collectionType = value.GetType().GenericTypeArguments.First();
var method = typeof(Enumerable).GetMethod("ToList");
var genericMethod = method.MakeGenericMethod(collectionType);
return (IList)genericMethod.Invoke(null, new[] { value });
}
這樣,您就可以遍歷集合。 如果屬性的類型為List
或Array
並且不需要創建新的集合,則可以將值IList
為IList
並對其進行迭代。
為了從數據庫上下文中獲取值,可以使用Set
方法:
var dbset = MyDbContext.Set(prop.PropertyType.GenericTypeArguments.First());
dbset
也可以傳遞給CollectionToList
方法,但是通過這種方式,您將從表中加載所有表行,這可能會花費大量時間和內存。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.