Entity framework 根据从函数获取的列类型更新 table
Entity framework update table based on the column type getting from function
大家好,我有一个 table 数据显示在网格中,它有将近 15 列,所以在单击每个 td 时,我将显示一个模式,以便用户可以更新和保存数据。我正在尝试编写一个通用函数,以便它将 ColumnName 和 ColumnValue 作为参数,这些参数将由 MVC 视图调用
[HttpPost]
Public JsonResult UpDateData(string ColumnName, string ColumnValue, int id)
{
var dbData = context.Table.Where(i=>i.Pid == id).FirstOrDefault();
Table t = new Table();
t = dbData;
t.SomeColumnName = ColumnValue; // Here I need a generic way to handle so that it should match the passed columnname, so that if I edit and pass another value it should accept
}
使用反射解决
[HttpPost]
Public JsonResult UpDateData(string ColumnName, string ColumnValue, int id)
{
var dbData = context.Table.Where(i=>i.Pid == id).FirstOrDefault();
var oType = dbData .GetType();
var prop = oType.GetProperty(ColumnName);
object convertedValue = Convert.ChangeType(ColumnValue,
prop.PropertyType);
prop.SetValue(dbData , convertedValue); //set the value
}
大家好,我有一个 table 数据显示在网格中,它有将近 15 列,所以在单击每个 td 时,我将显示一个模式,以便用户可以更新和保存数据。我正在尝试编写一个通用函数,以便它将 ColumnName 和 ColumnValue 作为参数,这些参数将由 MVC 视图调用
[HttpPost]
Public JsonResult UpDateData(string ColumnName, string ColumnValue, int id)
{
var dbData = context.Table.Where(i=>i.Pid == id).FirstOrDefault();
Table t = new Table();
t = dbData;
t.SomeColumnName = ColumnValue; // Here I need a generic way to handle so that it should match the passed columnname, so that if I edit and pass another value it should accept
}
使用反射解决
[HttpPost]
Public JsonResult UpDateData(string ColumnName, string ColumnValue, int id)
{
var dbData = context.Table.Where(i=>i.Pid == id).FirstOrDefault();
var oType = dbData .GetType();
var prop = oType.GetProperty(ColumnName);
object convertedValue = Convert.ChangeType(ColumnValue,
prop.PropertyType);
prop.SetValue(dbData , convertedValue); //set the value
}