0

I have a table in my database that defines the structure of the other tables. I want to be able to reuse code based on field type, but have no idea how to dynamically set the field to be used.

In my code, I want to be able to pass a function a table name, field name, and field value. The function will look up the field datatype and through a switch statement, pass the field name and field value to that case.

Right now, I am using the switch statement based on field name and then hardcoding everything in. This leads to A LOT of cases:

switch (passedfieldname) {
   case "tag4":
       var item = _context.Table.Where(i => i.Id == 13).SingleOrDefault();
       item.Tag4 = passedfieldvalue;
       _context.SubmitChanges();
       break;
}

What I would LIKE to be able to do is:

switch (fieldtype) {
   case "string":
       var item = _context.Table.Where(i => i.Id == 13).SingleOrDefault();
       item.passedfieldname = passedfieldvalue;
       _context.SubmitChanges();
       break;
}

IS there a simple solution to this?

Thanks for any help or even pointing me to the right documentation to read up on.

Dale K
  • 25,246
  • 15
  • 42
  • 71
Keith Clark
  • 609
  • 1
  • 7
  • 19
  • I assume `item.passedfieldname` is pseudo code for some arbitrary property/field identified by a string variable? If so, you should read up on reflection. – Kirk Woll Jan 25 '22 at 20:20
  • 1
    Something like this: https://stackoverflow.com/questions/7718792/can-i-set-a-property-value-with-reflection – Jack A. Jan 25 '22 at 23:50
  • @Jack A That was exactly what I was looking for !!!! Thank you – Keith Clark Jan 26 '22 at 02:21

0 Answers0