0
我已經在綁定到代表相當複雜的實體的POCO的頁面上有複雜的表單。其中一個要求是,在模糊的情況下,我更新數據庫。反射+實體框架來更新MVC應用程序中的數據
我目前通過ajax傳遞屬性(作爲鍵),值和CampaignId。密鑰可能類似於:Campaign.FanSettings.SocialSharing.FacebookLinkText
。
我正在使用下面的代碼,並得到「關閉」。我最終的PropertyToSet是FacebookLinkText沒有設置,因爲我的object source
是Entities.Campaign類型,而我的object value
只是一個字符串。我明白這些需要是同一類型的,但我不明白該怎麼做。兩個問題:
- 如何修改下面的代碼,以便能夠執行propertyToSet.SetValue方法
- 由於我鑄造這一個對象,我不知道如何做到這一點其實我的更新實體,所以當我調用SaveChanges時,它會適當更新。我錯過了什麼?
謝謝!
代碼:
public void UpdateCampaign(int id, string key, string value)
{
using (var context = new BetaEntities())
{
var camp = context.Campaigns.Where(e => e.Id == id).Single();
SetProperty(camp, key,value);
}
}
public void SetProperty(object source, string property, object value)
{
string[] bits = property.Split('.');
for (int i = 0; i < bits.Length - 1; i++)
{
PropertyInfo prop = source.GetType().GetProperty(bits[i]);
source = prop.GetValue(source, null);
}
PropertyInfo propertyToSet = null;
if (source is IEnumerable)
{
foreach (object o in (source as IEnumerable))
{
propertyToSet = o.GetType().GetProperty(bits[bits.Length - 1]);
break;
}
}
else
{
propertyToSet = source.GetType().GetProperty(bits[bits.Length - 1]);
}
propertyToSet.SetValue(source, value, null);
}