C# MongoDB Driver执行Lookup聚合与Cosmos DB Shell返回结果不一致
问题原因
你遇到的问题核心是C# MongoDB驱动反序列化时只会映射实体类中已定义的属性,你当前的ProductStemCollection实体类没有声明stems对应的属性,所以查询返回的stems字段会被直接忽略,不会出现在反序列化后的对象中。
解决方案
方案1:扩展原有实体类(推荐)
直接在ProductStemCollection类中添加关联结果对应的属性即可:
[BsonCollection( "ProductStemCollections" )] public class ProductStemCollection : Document { public string Name { get; set; } [BsonRepresentation( BsonType.String )] public List<ObjectId> ProductStems { get; set; } = new List<ObjectId>(); // 新增关联结果属性,BsonElement注解和lookup中as的字段名匹配 [BsonElement("stems")] public List<ProductStem> Stems { get; set; } = new List<ProductStem>(); }
如果你的MongoDB驱动配置了全局驼峰命名序列化规则,也可以省略[BsonElement("stems")]注解,驱动会自动将小写开头的stems字段映射到大驼峰的Stems属性。
方案2:不修改原有实体,用动态类型接收结果
如果你不想侵入原有实体定义,可以先将查询结果映射为BsonDocument或者自定义DTO,再做转换:
var query = prodStemCollectionRepo.Collection .Aggregate() .Lookup<ProductStemCollection, BsonDocument>( "ProductStems", "ProductStems", "_id", "stems" ); var results = await query.ToListAsync(); // 后续按需将BsonDocument转换为需要的结构
补充说明
你两个集合的关联字段都配置了[BsonRepresentation(BsonType.String)],存储的都是字符串格式的ObjectId,和Shell中执行查询的返回结果一致,关联逻辑本身没有问题,只需要补全属性映射即可。
内容的提问来源于stack exchange,提问作者Tungviktarn
相关产品推荐
相关产品推荐

