简体   繁体   English

如何在实体框架核心中使用私有属性更新 Model?

[英]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:我有一个 model 在 Id 属性上有一个私有设置器:

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

The Controller functionality is: Controller 功能是:

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.当我调用 controller 但是它使用新的 GuestId Guid 创建 class 的新实例,因此无法更新属性。

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.如果我删除了私有设置器,那么更新功能就可以正常工作,但我觉得更新 model 的想法并不是真正的最佳实践。

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.一种解决方案可能是在表单主体中采用通用 json object 然后更新每个单独的属性,但我认为它并不是真正可扩展的,因为每个 model 更新都意味着更新控制器。

What's the best way around this?解决这个问题的最佳方法是什么? Thank you!!!谢谢!!!

For FromBody , it uses Newtonsoft.Json to deserialize the json to Object.对于FromBody ,它使用Newtonsoft.Json将 json 反序列化为 Object。

To make Newtonsoft.Json to deserialize the private properties, you could try below;Newtonsoft.Json反序列化私有属性,你可以试试下面;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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