Home > Software engineering >  ASP.NET Core - using a form to partially update existing data
ASP.NET Core - using a form to partially update existing data

Time:06-10

How do I update a model partially using a form? In other words, how do I update the data in a database for a model that may have 50 fields, but I only want to update two of them via a form? I have a model that has a form. That model has 30 fields, but I only want to update the date of birth and a description in the model's data through the form.

How do I do that without having to grab the data from the database beforehand?

For example:

Applicant has 30 fields, but I only need to update the Applicant's last name and date of birth, so my form ONLY has these fields in it for updating. How do I update JUST those two fields without wiping out or using default values for the others? Is that a view model?

Thank you!

CodePudding user response:

Try Attach method. You will need to set primary key for the entity and mark fields you need to update as modified

var entity = new SomeEntity()
{
    Id = id, // primary key
    SomeProperty = newvalue,
};

dbContext.SomeEntities.Attach(entity);
dbContext.Entry(entity).Property(x => x.SomeProperty).IsModified = true;
dbContext.SaveChanges();
  • Related