我的MongoDB中有这样的文档结构:
{
"_id": {
"$oid": "6249f0df30dfe57eef463997"
},
"111-333": [{
"_id": "",
"id": 1,
"name": "iPhone 123",
"description": "Sample description",
"price": 100.0,
"imageUrl": "images/product_images/iphone.jpg",
"category": "Electronics",
"quantity": 1
},
{
"_id": "",
"id": 2,
"name": "iPhone 3",
"description": "Sample description 2",
"price": 50.0,
"imageUrl": "images/product_images/iphone.jpg",
"category": "Electronics",
"quantity": 1
}]
}
我正试图在C#模型类中阅读以下内容:
public class Orders
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
[BsonElement("_id")]
[JsonPropertyName("mongoId")]
public string? MongoId { get; set; }
[BsonDictionaryOptions(DictionaryRepresentation.Document)]
public Dictionary<String, List<Product>> Order;
public Orders(String MongoId, Dictionary<String, List<Product>> Order)
{
this.MongoId = MongoId;
this.Order = Order;
}
}
因此,基本上,“id”是用“MongoId”映射的,现在我想将整个字典映射到变量“Order”,但当我尝试调用
GET API
,引发以下错误:
System.FormatException: Element '111-333' does not match any field or property of class marketplace_services_CSI5112.Models.Orders. at
MongoDB.Bson.Serialization.BsonClassMapSerializer`1.DeserializeClass(BsonDeserializationContext context) at
MongoDB.Bson.Serialization.BsonClassMapSerializer`1.Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
有人能帮忙吗!!!!我甚至尝试过使用
[BsonExtraElements]
但这对我不起作用。
产品型号:
using System;
using System.Text.Json.Serialization;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace marketplace_services_CSI5112.Models
{
public class Product
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
[BsonElement("_id")]
[JsonPropertyName("mongoId")]
public string? MongoId { get; set; }
[BsonElement("id")]
[JsonPropertyName("id")]
public int Id { get; set; }
[BsonElement("name")]
[JsonPropertyName("name")]
public string Name { get; set; }
[BsonElement("imageUrl")]
[JsonPropertyName("imageUrl")]
public string ImageUrl { get; set; }
[BsonElement("description")]
[JsonPropertyName("description")]
public string Description { get; set; }
[BsonElement("category")]
[JsonPropertyName("category")]
public string Category { get; set; }
[BsonElement("price")]
[JsonPropertyName("price")]
public double Price { get; set; }
[BsonElement("quantity")]
[JsonPropertyName("quantity")]
public int Quantity { get; set; }
public Product(String MongoId, int Id, string Name, string Description, double Price, string ImageUrl, string Category, int Quantity)
{
this.MongoId = MongoId;
this.Id = Id;
this.Name = Name;
this.Description = Description;
this.Price = Price;
this.ImageUrl = ImageUrl;
this.Category = Category;
this.Quantity = Quantity;
}
}
}