如何在C# MongoDB模型中声明数组的数组(Azure Cosmos DB场景)
解决方案
首先,你需要先定义一个用于表示单个坐标的实体类,用来映射JSON里的lat和lon字段:
namespace GeofencedLocations.Models { public class Coordinate { [BsonElement("lat")] public string Latitude { get; set; } [BsonElement("lon")] public string Longitude { get; set; } } }
接下来修改Geofence类中的LocationCoordinates字段类型,将其改为Coordinate类型的集合(数组或泛型列表都可以):
namespace GeofencedLocations.Models { public class Geofence { [BsonId] [BsonRepresentation(BsonType.ObjectId)] public string LocationId { get; set; } [BsonElement("Location name")] public string LocationName { get; set; } [BsonElement("Location Coordinates")] // 可以用数组或者 List<Coordinate>,根据需求选择 public Coordinate[] LocationCoordinates { get; set; } // 或者泛型列表写法:public List<Coordinate> LocationCoordinates { get; set; } [BsonElement("user ID")] public string userID { get; set; } } }
说明
- 定义
Coordinate类是为了和你提供的JSON结构精准映射,每个坐标对象对应lat和lon两个字符串字段 - 选择数组还是
List<Coordinate>取决于业务场景:泛型列表在增删元素时更灵活,数组适合固定长度的坐标集合 - 保留
BsonElement特性能确保实体类属性和Cosmos DB(MongoDB API)中的字段名一一对应
内容的提问来源于stack exchange,提问作者Muskan
相关产品推荐
相关产品推荐

