c# - 遍历字典并将项目附加到对象

时间:2014-11-19 21:27:16

标签: c# dictionary

我有一个实体框架对象" user"。我在字典中传递变量来更新用户。我想遍历字典项并将它们附加到实体框架对象。

因此,如果一个项目有一个id,它将被更新,否则它将被插入

词典项目:

Dictionary<string, string> updateItems = new Dictionary<string, string>();
updateItems.Add("column1", "value1");
updateItems.Add("column2", "value2");

功能:

public static void markPost(Dictionary<string, string> data)
{
  using (var db = new DB())
  {
    var user = new user();   

    if (data.ContainsKey("id"))
    {          
      user = db.user.Find(Int32.Parse(data["id"])); 
    }

    foreach (KeyValuePair<string, string> entry in data)
    {
      if (!entry.Key.Equals("id"))
      {
        PropertyInfo propertyInfo = user.GetType().GetProperty(entry.Key);
        propertyInfo.SetValue(user, entry.Value, null); 
      }          
    }

    if (!data.ContainsKey("id"))
    {
      db.user.Add(user);
    } 

    db.SaveChanges();
  }
}

1 个答案:

答案 0 :(得分:1)

在你的foreach循环中,尝试

PropertyInfo propertyInfo = user.GetType().GetProperty(entry.Key);
propertyInfo.SetValue(user, entry.Value, null);  //Assumes the value is of the same type as the property.

您需要System.Reflection的using指令。