Linq 更新动态列问题

Linq 更新动态列问题,linq,entity-framework,Linq,Entity Framework,我正在尝试更新表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 = columnVal

我正在尝试更新表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();
}
public void updateEmployees(列表columnDb,列表columnValues)
{
var data=ctx.tblEmployee.Where(e=>e.Id==empId);
....
data.columnDb=columnValues;//伪
ctx.tblEmployee.Add(数据);
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]);
    }
}

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

为什么不更新所有列,甚至是数据未更改的列?只需将已经存在的db值传递到不需要更新的位置。
List columnDb
不包含所有列,因此无法更新所有列。