0

I have a form and multiple textboxes in it each textbox represents a specific column of a table. for example Textbox of FirstName and its ID='Name' and the column name of Firstname in DB is Name. Now what I am doing is I am sending column value(Whatever user write) and column name (ID of that column) to the function which will save the value in the database.

Here are my steps 1.I get a record on the bases of the DB id which record to update.

var table = _db.Table.Where(x => x.ID == ID).FirstOrDefault();

2.I have all column's names of that table using this.

var names = typeof(User).GetProperties()
                    .Select(property => property.Name)
                    .ToArray();

3.Iterated through columns and match that ID of the column with DB Columns if that matches then I have to update that particular column.

      foreach (var item in names.ToList())
        {
            if (item.Equals(ID))
            {
                table. = TextFieldValue;//here i am stuck 
                table.Name= TextFieldValue;// i have to update table field like this
            }

        }

I don't want to use a switch or if-else as there are too many columns in the table.

Farruk
  • 31
  • 1
  • 9
  • 1
    Here are some information to set the property value using InvokeMember https://stackoverflow.com/questions/619767/set-object-property-using-reflection Just a word of caution, using reflection may be slower than just mapping the values and saving a record. Unless you are actively trying to audit what value were updated, and what it was changed to/from this seems like overkill for most crud operations. – Anthony G. Sep 28 '22 at 16:35
  • Don't use `var` until you know what type you get. Here `names` will be a `PropertyInfo[]` and `ìtem` will be a `PropertyInfo`. Now you should be able to search for solutions. – Poul Bak Sep 28 '22 at 17:17
  • BTW: You don't need `.ToList()` since you can iterate an `Array`. – Poul Bak Sep 28 '22 at 17:19
  • Is it EF6 or EF Core? – Alexander Petrov Sep 29 '22 at 13:36
  • Problem solved? Give a response. – Alexander Petrov Oct 02 '22 at 19:29

1 Answers1

0

No need reflection.
Try this:

context.Entry(entity).Property(propertyName).CurrentValue = someValue;
Alexander Petrov
  • 13,457
  • 2
  • 20
  • 49