Thursday, March 8, 2018

Updating records in Db deletes unmodified column values

I'm editing db records through a post action. I am using asp.net core 2.

For simplicity sake say I have

person { Id : 3, Name: "John Smith", PhoneNumber: "ThisIsANumber" } 

And I want to update PhoneNumber. If I try this in the action controller with DbContext.Update() it deletes the name value. It seems this only replaces the record, not update.

for example, in postman I post

{ id:3, phoneNumber: "numberHere" } 

In the database, person is now

person { id:3, phoneNumber: "numberHere" } 

The name field has been deleted.

I have tried

_context.update(model); 

I have also tried

_ctx.Entry(model).State = EntityState.Modified; 

I've also tried Microsoft's example

 var studentToUpdate = await _context.Students.SingleOrDefaultAsync(s => s.ID == id); if (await TryUpdateModelAsync<Student>( studentToUpdate, "", s => s.FirstMidName, s => s.LastName, s => s.EnrollmentDate)) { try { await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } 

For some reason this doesn't work for me. Inside the TryUpdateModelSync method I don't get options to do

s => s.Name, s=> s.PhoneNumber 

Instead I get options like

s => s.ConvertEmptyStringToNull, s => s.DataTypeName 

No fields that are relevant to my model.

So I have two questions here. Is there something wrong with Microsoft's example that doesn't work in anymore? More importantly, how can I implement a solution to update records without having to specify every property value?

Updating records in Db deletes unmodified column values Click here
  • Blogger Comment
  • Facebook Comment

0 comments:

Post a Comment

The webdev Team