1

一个有点做作但仍然很重要的例子。

假设以下情况UserDetails是 RESTful Web 服务使用的聚合 DTO(不确定术语是否正确,请教育我,但基本上是从不同商店/服务收集信息的模型)。它不一定与它收集在一起的对象具有相同的属性名称。

public class UserDetails
{
    public int UserId { get;set; }
    public string GivenName { get; set; }
    public string Surname { get; set; }
    public int? UserGroupId { get;set; } // FK in a different database
}

让我们的商店持久化以下模型:

public class User
{
    public int Id { get; set; }
    public string GivenName { get; set; }
    public string Surname { get; set; }
}


public class UserGroup
{
    public int UserId { get; set; }
    public int GroupId { get; set; }
}

让 UserDetails 对象被这样填充:

User user = _userService.GetUser(userId) ?? throw new Exception();
UserGroup userGroup = _userGroupService.GetUserGroup(user.Id);

UserDetails userDetails = new UserDetails {
    UserId = user.Id,
    GivenName = user.GivenName,
    Surname = user.Surname,
    UserGroupId = userGroup?.GroupId
};

也就是说,设置FirstNameorSurname应该委托给,UserService和.UserGroupIdGroupService

这个UserDetails对象用于 GET 和 PUT,这里的逻辑非常简单,但是这个对象的 JSON Patch 文档是为 PATCH 请求发送的。这显然要复杂得多。

我们如何才能改变用户组?我想出的最好的(“最好的”被非常松散地使用)是这样的:

int userId;
JsonPatchDocument<UserDetails> patch;

// This likely works fine, because the properties in `UserDetails`
// are named the same as those in `User`
IEnumerable<string> userPaths = new List<string> {"/givenName", "/surname"};
if (patch.Operations.Any(x => userPaths.Contains(x.path))) {
    User user = _userService.GetUserByUserId(userId);
    patch.ApplyTo(user);
    _userService.SetUser(userId, user);
}

// Do specialised stuff for UserGroup
// Can't do ApplyTo() because `UserDetails.UserGroupId` is not named the same as `UserGroup.GroupId`
IEnumerable<Operation<UserDetails>> groupOps = patch.Operations.Where(x => x.path == "/userGroupId");
foreach (Operation<UserDetails> op in groupOps)
{
    switch (op.OperationType)
    {
        case OperationType.Add:
        case OperationType.Replace:
            _groupService.SetOrUpdateUserGroup(userId, (int?)(op.value));
            break;

        case OperationType.Remove:
            _groupService.RemoveUserGroup(userId);
            break;
    }
}

这是非常可怕的。这是很多样板,并且依赖于魔术字符串。

无需请求更改Microsoft.AspNetCore.JsonPatchAPI,例如

JsonPatchDocument<UserDetails> tmpPatch = new JsonPatchDocument<UserDetails>();
tmpPatch.Add(x => x.GivenName, String.Empty);
tmpPatch.Add(x => x.Surname, String.Empty);
IEnumerable<string> userPaths = tmpPatch.Operations.Select(x => x.path);

至少会摆脱魔法弦,但是,imo,这感觉不对!

JsonPatch 在这方面似乎非常有限,似乎更适合 DAO(实体)和 DTO(模型)之间存在 1:1 映射的系统。

有人有什么好主意吗?不能很难打败我想出的牛肚!!

4

1 回答 1

0

Json Merge Patch - RFC7396 would be more suited to this.

于 2017-09-15T23:44:07.260 回答