Redis实现中Put请求报错:Id字段未正确填充问题求助
问题分析与解决方案
问题根源
你的Brand模型未明确标记主键字段,Redis OM无法识别Id作为定位Redis记录的依据,导致即使请求体传入了Id值,框架仍无法正确执行更新操作,抛出Id field is not correctly populated异常。
解决方案
1. 为Id字段添加主键标记
在Brand类的Id属性上添加[RedisIdField]特性,明确该字段为Redis文档的主键:
[Document(StorageType = StorageType.Json, Prefixes = new[] { "Brand" })] public class Brand { [RedisIdField] // 新增主键标记特性 [Indexed] public int Id { get; set; } [Indexed] public string? Name { get; set; } [Indexed] public string? IsRegistered { get; set; } [Indexed] public string? About { get; set; } [Indexed] public List<string>? Countries { get; set; } }
2. 重建Redis索引
修改模型后需要删除旧索引并重新创建:
- 通过Redis CLI或Redis Desktop Manager执行命令删除旧索引:
FT.DROPINDEX Brand-idx - 重启API服务,让
IndexCreationService重新生成Brand的索引。
3. 优化异常处理
控制器的catch块中直接throw ex;会破坏原始异常的堆栈信息,建议改为:
catch (Exception ex) { throw; // 保留完整堆栈信息 }
额外检查点
- 确认Postman请求中的
Id值与Redis中已存在的记录Id完全匹配(注意类型一致性,此处为int类型,值1是合法的)。 - 验证
_brandCollection是正确的Redis OM集合类型(如RedisCollection<Brand>)且注入逻辑无误。
内容的提问来源于stack exchange,提问作者Wasim
相关产品推荐
相关产品推荐

