Azure Mobile App Services中如何移除Delta对象的指定属性
解决Azure Mobile App Services中Delta对象移除null字段的问题
我刚好处理过类似的场景,给你分享一个简单直接的解决方案:我们可以通过遍历Delta对象的变更属性,筛选出值为null的字段并移除它们,这样在执行Patch操作时就不会把这些null值应用到实体上了。
具体实现步骤
在你的ApiController的Patch方法中,在调用patch.Patch(entity)之前,加入这段处理逻辑:
public async Task<IHttpActionResult> PatchMyBean(string id, Delta<MyBean> patch) { // 从数据库获取目标实体 var entity = await dbContext.MyBeans.FindAsync(id); if (entity == null) { return NotFound(); } // 筛选出Delta中值为null的属性 var nullPropertyNames = patch.GetChangedPropertyNames() .Where(propertyName => { if (patch.TryGetPropertyValue(propertyName, out var propertyValue)) { return propertyValue == null; } return false; }) .ToList(); // 移除所有值为null的属性 foreach (var propertyName in nullPropertyNames) { patch.RemoveProperty(propertyName); } // 应用补丁到实体 patch.Patch(entity); await dbContext.SaveChangesAsync(); return Ok(entity); }
代码说明
GetChangedPropertyNames():这个方法会返回Delta对象中所有来自请求体的属性(也就是你JSON里传的那些字段,包括继承自EntityData的CreatedAt这类父类属性)。TryGetPropertyValue():安全地获取属性的值,避免直接访问可能不存在的属性抛出异常。RemoveProperty():把值为null的属性从Delta中移除,这样后续执行Patch()时就不会更新这些字段了。
这个方案不需要修改微软库的EntityData类,完全在你的业务代码层处理,既符合PATCH请求的语义,又能精准过滤掉不需要的null字段。
内容的提问来源于stack exchange,提问作者Cristiano Ghersi
相关产品推荐
相关产品推荐

