To simplify the problem, in C# I have a model like this
public class Person
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
[MaxLength(128)]
public string? Id { get; set; }
[MaxLength(256)]
public string PersonName { get; set; }
public short PersonAge { get; set; }
// ommitted other properties
now, I have a form like this in ASP Core in the frontend
@model Person
<form action="/api/new-person">
<input form="PersonName"/>
<button type="submit"></button>
</form>
As you can see, I only have PersonName
in my form, in my backend I only want to be able to update the Person
object in my database for the value of PersonName
because it is property that exists in the form, again, this is a simplified example because my object is massive and it changes just about all the time not to mention a lot of foreign keys, now, I don’t want to painstakingly set each properties in the backend such as
var existingPersonFromDatabase = await _appDbContext.User.FirstOrDefaultAsync(x=>x.Id == formPerson.Id);
existingPersonFromDatabase.PersonName = formPerson.PersonName;
existingPersonFromDatabase.PersonAge = formPerson.PersonAge ;
// + settings 20 more properties one by one
so the question here is, how do i make it so that i only have to update the fields existing in the form?
2
Answers
I found the answer, for some reason this is not well documented by Microsoft and its hidden below the docs, I used
TryUpdateModelAsync
in theController
,inside the controller you can have
below is my complete code
You could cycle through the properties of the form with the reflection, then in the model, search for the properties with same name and type and then assign them.
An example for this could be something like this:
Otherwise you could use a library like automapper to do the job for you with an automatic map.