Hello,
I wish to update a particular field in DB by passing the field name and value. How can I make below work ?
await _context.
Hello,
I wish to update a particular field in DB by passing the field name and value. How can I make below work ?
await _context.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Mayooran NavamanyRank #438 · 5.7K reputationPosted Jun 19, 2024, 11:17 PM EDT
Here's how you can achieve this using reflection:
Below is an example of how you can implement this:
public async Task UpdateFieldAsync(string entityName, int entityId, string propertyName, object propertyValue) { // Retrieve the entity var entity = await _context.Set(entityName).FindAsync(entityId); if (entity == null) { throw new Exception("Entity not found"); } // Use reflection to set the property value var propertyInfo = entity.GetType().GetProperty(propertyName); if (propertyInfo == null) { throw new Exception("Property not found"); } // Set the property value propertyInfo.SetValue(entity, Convert.ChangeType(propertyValue, propertyInfo.PropertyType), null); // Save the changes await _context.SaveChangesAsync(); }Here’s how you can call this method:
await UpdateFieldAsync("YourEntityName", request.reportfield.Id, request.reportfield.Name, request.reportfield.Value);Explanation
Retrieve the Entity:
var entity = await _context.Set(entityName).FindAsync(entityId);This line retrieves the entity from the database using its ID.
Use Reflection to Set the Property:
var propertyInfo = entity.GetType().GetProperty(propertyName); if (propertyInfo == null) { throw new Exception("Property not found"); } propertyInfo.SetValue(entity, Convert.ChangeType(propertyValue, propertyInfo.PropertyType), null);This code uses reflection to find the property by name and set its value. The
Convert.ChangeTypemethod is used to ensure the value is of the correct typeSave Changes:
await _context.SaveChangesAsync();This line saves the changes back to the database.
Note