0

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!

tahdhaze09
  • 2,220
  • 1
  • 21
  • 36
  • 1
    Does this answer your question? [Update a record without first querying?](https://stackoverflow.com/questions/4218566/update-a-record-without-first-querying) – Yehor Androsov Jun 08 '22 at 12:39

1 Answers1

1

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();
Yehor Androsov
  • 4,885
  • 2
  • 23
  • 40
  • Thanks! So, for any of the properties I'm changing, they are listed as: dbContext.Entry(entity).Property(x => x.SomeProperty1).IsModified = true; dbContext.Entry(entity).Property(x => x.SomeProperty2).IsModified = true; and so on. – tahdhaze09 Jun 08 '22 at 18:31
  • @tahdhaze09 thats correct – Yehor Androsov Jun 08 '22 at 19:13