我正在尝试更新表 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();
}
如何更新作为参数动态传递的列?
最佳答案
您可以利用反射的力量来做到这一点。
只需迭代对象的属性并为列表中的属性设置值即可。
首先,让我们使用参数中的属性名称和值构建一个字典,以便更轻松地访问值:
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]);
}
}
当然,上面的代码假设字符串
和数据对象的属性类型之间存在转换。
关于linq - 更新动态列问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26293792/