[英]Find a collection property using reflection then add to collection
我正在嘗試創建一個通用函數以在實體框架中添加關系記錄。 我正在研究以下解決方案。 盡管如果我要解決這個問題,您可以將我的方向正確嗎?
我上課有以下內容。 還要注意,這是實體框架中的代碼優先方法。
public class MainTable
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int MainTableID { get; set; }
public int LookupID { get; set; }
[ForeignKey("LookupID")]
public virtual LookupTable Lookups { get; set; }
}
public class LookupTable
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int LookupID{ get; set; }
public string LookupText { get; set; }
public virtual ICollection<MainTable> MainTable { get; set; }
}
然后,我有以下代碼,試圖在MainTable和LookupTable之間添加關系。 我首先傳遞兩種表類類型,並傳遞要添加的記錄和collection屬性的名稱。
問題是每當我嘗試將其轉換為(ICollection(MainTable))時,“ collectionField”為NULL。 我需要“ collectionField”成為ICollection(MainTable)類型,以便可以添加MainTable記錄,除非我以錯誤的方式進行操作。
public void AddRelationalRecord<MainTableType, LookupTableType>(MainTableType recordToAdd, string collectionFieldName)
where MainTableType: class
where LookupTableType: class
{
var collectionField = typeof(LookupTableType)
.GetProperties()
.Where(prop => prop.Name == collectionFieldName)
.FirstOrDefault();
collectionField.Add(recordToAdd);
}
根據評論,我決定更改此方法。 如果有人感興趣,下面的代碼將起作用。
public void AddRelationalRecord(object recordToAdd, object recordWithCollection, string collectionFieldName)
{
var collectionProp = recordWithCollection.GetType().GetProperty(fieldName);
collectionProp.PropertyType.GetMethod("Add").Invoke(aaa.GetValue(recordWithCollection, null), new object[] { recordToAdd });
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.