1

I want to update a column which is dynamic. In my employee table I have various columns, which column to update depends on selection so it is dynamic.

In employee table, I have 5 columns - Id, name, desig, depart, Sal

So in case I have to update desig column :-

string columnName = "desig"; // This comes as a parameter. This is a dynamic Value. This is just an example.

var data = ctx.tblEmp.Where(e => e.Id == model.Id).Select(e => e).SingleOrDefault();

data.desig = 'NewValue';

ctx.tblEmp.Attach(data);
...
ctx.SaveChanges();
ekad
  • 14,056
  • 26
  • 43
  • 45
Anup
  • 8,818
  • 16
  • 63
  • 126

1 Answers1

1

Since there are only 5 constant columns, I would go with the simple solution:

var data = ctx.tblEmp.SingleOrDefault(e => e.Id == model.Id);
switch (columnName)
{
    case "Id":
       data.id = newValue; //newValue should have a correct type.
       break;
    case "name": 
       data.name = newValue; 
       break;
    case "desig":
       data.desig = newValue; 
       break;
    case "depart":
       data.depart = newValue; 
       break;
    case "Sal":
       data.Sal = newValue; 
       break;
}
Ofiris
  • 5,907
  • 5
  • 34
  • 57
  • Indeed there are more columns in my table...But i will go with this strategy..! – Anup Oct 07 '14 at 06:02
  • Ok, note that if you had many columns or many tables, Reflection could help: http://stackoverflow.com/questions/1196991/get-property-value-from-string-using-reflection-in-c-sharp – Ofiris Oct 07 '14 at 06:12