2014-10-10 73 views
2

我正在尝试更新表emp中的值。哪一列要更新是动态的。更新动态列问题

public void updateEmployees(List<String> columnDb, List<String> columnValues) 
{ 
    var data = ctx.tblEmployee.Where(e => e.Id == empId).Select(e => e).SingleOrDefault(); 
    .... 

    data.columnDb = columnValues; // Pseudo  

    ctx.tblEmployee.Add(data); 
    ctx.SaveChanges(); 
} 

如何更新作为参数动态传递的列?

+0

为什么不更新所有的列,甚至没有更改数据的列?只需传递您不需要更新的现有数据库值即可。 – ilans 2014-10-10 08:17:46

+0

'List columnDb'不包含所有列,所以我无法更新所有列。 – Anup 2014-10-10 08:33:47

回答

2

你可以用Reflection的力量做到这一点。

只需遍历对象的属性并设置列表中属性的值即可。

首先,让我们建立与属性名称和值的字典从您的参数,使该值的访问更加容易:

var values = columnDb.Zip(columnValues, 
     (name, value) => new { Name = name, Value = value }) 
     .ToDictionary(x => x.Name, x => x.Value); 

现在,通过属性迭代并设定值:

var data = ctx.tblEmployee.SingleOrDefault(e => e.Id == empId); 
foreach(PropertyInfo property in data.GetType().GetProperties()) 
{ 
    // Check if property should be updated 
    if(values.ContainsKey(property.Name)) 
    { 
     var value = values[property.Name]; 
     // Change the type of the value to the type of the property 
     object converted = Convert.ChangeType(value, property.PropertyType); 
     // Set the property value 
     property.SetValue(data,values[property.Name]); 
    } 
} 

当然,上面的代码假定在string和数据对象的属性类型之间存在转换。