Home > Blockchain >  How to update just selected field in the passed ViewModel
How to update just selected field in the passed ViewModel

Time:11-16

I have a viewmodel to update data (from API, not view) with params like below:

public string Name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }

i just want to update "name", so my param like below:

{
  "name": "my name"
}

its name changed become "my name" but its email and phone become null. how to avoid params changed to be null if they don't exist in input form? Thanks...

CodePudding user response:

You'll have to adjust whatever does the update so that it understands "null means do not set a value, rather than set the value to null"

For example if you're running a db update query you could:

UPDATE person
SET 
  name = COALESCE(@name, name),
  email = COALESCE(@email, email),
  phone = COALESCE(@phone, phone)
WHERE 
  id = @id

Now if any value is supplied as null the update will set the column to the same value it is currently (ie no-op)

If you're adjusting a c# object you can take a similar approach:

 var p = db.FindPerson(viewmodel.PersonId);

 p.Name = viewmodel.Name ?? p.Name;
 ...
    

CodePudding user response:

As I see, you have a problem or misunderstanding in your software design.

If this API endpoint is meant to just update the name field, then you should not have the other fields in your ViewModel. However, if you update the other fields in some cases, then you should pass their values as well.

So maybe you need to call a Get endpoint first to get the all data you need in your client "web page for example" and then allow this client to resend the full JSON, not just the name. Or you may just need an endpoint that just takes the name.

Another solution, in case you're using EF, is to ignore the null fields when updating the EF entity. e.g.

...
var entity = dbContext.Employees.FirstOrDefault(e => e.Id == 3);
entity.Name = request.Name;
await dbContext.SaveChangesAsync();
...
  • Related