Get Object在ASP.NET API MongoDB中具有对象数组

vhmi4jdf  于 2022-10-04  发布在  .NET
关注(0)|答案(1)|浏览(114)

我想在MongoDB中获取所有购物车对象,但结果缺少项目列表

示例数据MongoDB:

{
  "_id": "temp",
  "total": "2300000",
  "buyer": "test",
  "items": [
    {
      "name": "IP-8",
      "amount": "2",
      "price": "20000"
    },
    {
      "name": "IP-12",
      "amount": "2",
      "price": "20000"
    }
  ]
}

结果:

[{"id":"temp","buyer":"test","total":2300000}]

这里有两个类:

public class Carts
{
    [BsonId]
    public string Id { get; set; }
    public string buyer { get; set; }
    public double total { get; set; }
    [BsonElement("items")]
    List<CartItem> items { get; set; }

}

public class CartItem
{
    [DataMember]
    public string name { get; set; }

    [DataMember]
    public int amount { get; set; }

    [DataMember]
    public double price { get; set; }
}

函数类:

public class TempCartService
{
    private readonly IMongoCollection<Carts> _temp;
    //private readonly IMongoCollection<CartItem> _items
    public TempCartService(IOptions<ShopDbSetting> options)
    {
        var mongoClient = new MongoClient(options.Value.ConnectionString);
        _temp = mongoClient.GetDatabase(options.Value.DatabaseName)
            .GetCollection<Carts>("Carts");
    }
    public async Task<List<Carts>> FindAll() =>
      await _temp.Find(_ => true).ToListAsync();
}
lmvvr0a8

lmvvr0a81#

请将您的可访问修饰符更改为public,请参见以下代码

public class Carts
{
    [BsonId]
    public string Id { get; set; }
    public string buyer { get; set; }
    public double total { get; set; }
    [BsonElement("items")]
    public List<CartItem> items { get; set; }

}

public class CartItem
{
    [DataMember]
    public string name { get; set; }

    [DataMember]
    public int amount { get; set; }

    [DataMember]
    public double price { get; set; }
}

相关问题