在实体框架中将键值对与实体属性映射

时间:2018-06-28 13:43:58

标签: sql-server asp.net-mvc entity-framework asp.net-web-api ef-database-first

下面是我的实体代码和一个需要从键值对映射实体 TblEmployee 的函数。

在foreach循环中,我正在基于键获取值,什么是最好的方法?

  public class TblEmployee
            {       
                public int EmployeeId { get; set; }
                public string Name { get; set; }      
            }
 public int Create()      
        {
          tblEmployee employee = new tblEmployee();
                    using (var ctx = new theparkeee_testEntities())
                    {
                        foreach (string key in HttpContext.Current.Request.Form.AllKeys)
                        {
                            string value = HttpContext.Current.Request.Form[key];
                            //how to map value from key value pair to entity employee.
                        }
                    }
         }

1 个答案:

答案 0 :(得分:1)

您可以使用System.Reflection使用Type.GetProperty(string name)来获取对象的属性。拿到PropertyInfo后,您可以使用SetValue为其分配一个值。

foreach (string key in HttpContext.Current.Request.Form.AllKeys) {

     // note that "value" is a reserved word, do not use it as variable name
    string val = HttpContext.Current.Request.Form[key];

    var propertyInfo = typeof(TblEmployee).GetProperty(key); // can maybe be moved outside of the loop
    if (propertyInfo != null) {
        propertyInfo.SetValue(employee, val); 
    }
}

这将适用于字符串属性。如果该属性是另一种类型,则必须找到正确的类型(再次使用反射),并在分配值之前强制转换字符串值。

请注意,这不是在MVC中存储数据的正确方法。您不应该直接使用Request.Form,而是您的POST操作应该接受可以映射(例如,使用Automapper)到数据库实体的ViewModel。即让ASP ModelBinder来工作,而不是浪费时间!

[HttpPost]
public ActionResult Submit(MyViewModel postData) {
    var employee = Mapper.Map<TblEmployee>(postData);
    _ctx.Employees.Add(employee);
    _ctx.SaveChanges();
    return new HttpStatusCodeResult((int)HttpStatusCode.OK);
}