Partial Entity Updates in WebAPI PUT/POST

前端 未结 2 2021
梦如初夏
梦如初夏 2020-12-24 08:38

Say you have a repository method to update a Document:

public Document UpdateDocument(Document document)
  {
  Document serverDocument = _db.Documents.Find(         


        
2条回答
  •  攒了一身酷
    2020-12-24 09:00

    Is this cool, or is there a pattern/practice that I haven't learned about yet that might facilitate partial updates by sending only what is needed over the wire?

    A good practice of doing a POST or PUT is to only include values that you need for that specific request. In doing the UpdateDocument you should ask yourself what "really should be done here"? If you have a hundred fields on that object do you need to update all of them or only part of them. What "action" are you really trying to do?

    Let's have an illustration for those questions, say we have a User object that has the following fields:

    public class User {
        public int Id {get;set;}
        public string Username {get;set;}
        public string RealName {get;set;}
        public string Password {get;set;}
        public string Bio {get;set;}
    }
    

    You then have two use cases:

    1. Update the profile of a User
    2. Update the password of a User

    When you do each of those you will not, or it's a good idea to, have one update method that will do both. Instead of having a generic UpdateUser method you should have the following methods:

    1. UpdateProfile
    2. UpdatePassword

    Methods that accepts fields that they just need, nothing more, nothing less.

    public User UpdateProfile(int id, string username, string realname, string bio) {
    }
    public User UpdatePassword(int id, string password) {
    }
    

    Now comes the question:

    I have a use case that a "user action" allows for an update on multiple fields where some of the fields can have "no input" from the user but I don't want to update that field in my model.

    Suppose a user updates his/her profile and provided values for Username, RealName but not for Bio. But you do not want to set Bio as null or empty if it has a value already. Then that becomes a part of your application's business logic and that should be handled explicitly.

    public User UpdateProfile(int id, string username, string realname, string bio) {
        var user = db.Users.Find(id);
        // perhaps a validation here (e.g. if user is not null)
        user.Username = username;
        user.RealName = realname;
        if (!string.IsNullOrEmptyWHiteSpace(bio)) {
            user.Bio = bio;
        }
    }
    

提交回复
热议问题