简体   繁体   中英

How To Update A Model With Private Properties in Entity Framework Core?

I have a model that has a private setter on the Id property:

public class Guest
{
    public Guid GuestId { get; private set; } = Guid.NewGuid();
}

The Controller functionality is:

public ActionResult UpdateGuest([FromBody] Guest guest)
{
    _db.Guests.Update(guest);
    _db.SaveChangesAsync();

    return Ok();
}

When I call the controller however it creates a new instance of the class with a new GuestId Guid and therefore can't update the property.

If I remove the private setter then the update functionality works fine, but I feel like updating a model idea isn't really best practice.

One solution may be to take a generic json object in the form body and then update each individual property, but I reckon that it isn't really extensible as every model update would mean an update to the controllers.

What's the best way around this? Thank you!!!

For FromBody , it uses Newtonsoft.Json to deserialize the json to Object.

To make Newtonsoft.Json to deserialize the private properties, you could try below;

public class Guest
{
    [JsonProperty]
    public Guid GuestId { get; private set; } = Guid.NewGuid();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM