【发布时间】:2019-04-26 14:36:30
【问题描述】:
如何使用 C# 在 MongoDB 中的对象的项目数组中包含一个新项目?
我尝试使用 AddToSet 方法,但没有成功。
我的代码结构如下:
1 - 父对象(Revenda):
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using System.Collections.Generic;
namespace api.mstiDFE.Entidade.api.mstiDFE
{
public class Revenda : Notificavel, IEntidade
{
public Revenda(string Id, long Codigo, string CPF, string CNPJ, List<RevendaCliente> Clientes)
{
this.Id = Id;
this.Codigo = Codigo;
this.CPF = CPF;
this.CNPJ = CNPJ;
this.Clientes = Clientes;
}
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; private set; }
[BsonElement("Codigo")]
public long Codigo { get; private set; }
[BsonElement("Nome")]
public string Nome { get; private set; }
[BsonElement("CPF")]
public string CPF { get; private set; }
[BsonElement("CNPJ")]
public string CNPJ { get; private set; }
[BsonElement("Clientes")]
public ICollection<RevendaCliente> Clientes { get; private set; }
}
}
2 - 子对象 (RevendaCliente):
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using System.Collections.Generic;
namespace api.mstiDFE.Entidade.api.mstiDFE
{
public class RevendaCliente : Notificavel, IEntidade
{
public RevendaCliente(string Codigo, string Nome, string CPF, string CNPJ, ICollection<RevendaClienteToken> Tokens)
{
this.Codigo = Codigo;
this.Nome = Nome;
this.CPF = CPF;
this.CNPJ = CNPJ;
this.Tokens = Tokens;
}
[BsonElement("Codigo")]
public string Codigo { get; private set; }
[BsonElement("Nome")]
public string Nome { get; private set; }
[BsonElement("CPF")]
public string CPF { get; private set; }
[BsonElement("CNPJ")]
public string CNPJ { get; private set; }
[BsonElement("Tokens")]
public ICollection<RevendaClienteToken> Tokens { get; private set; }
}
}
3 - 用于插入完整父对象的代码:
public Revenda Add(Revenda revenda)
{
Database.GetCollection<Revenda>("Revendas").InsertOne(revenda);
return revenda;
}
4 - 用于恢复特定经销商的代码:
public Revenda FindById(string id)
{
return CollRevendas.Find<Revenda>(revenda => revenda.Id == id).FirstOrDefault();
}
一切正常。
但是,如何在已在 MongoDB 中注册的父对象 (Revenda) 中仅包含新的子对象 (RevendaCliente)?
我正在使用以下环境: -Microsoft.AspNetCore.App (2.1.1) -MongoDB.Driver (2.8.0)
【问题讨论】:
-
您的意思是向
MongoDB文档添加子对象?也许获取父对象(Revenda)并添加新的子对象并更新它 -
是的,完全正确。这是我做不到的。将存储在 MongoDB 中的对象的内存引用带到 C# 上下文中,并在其属性之一中包含一个新的复杂对象,在“Clientes”的情况下,这是我目前用来检索完整“Revenda”对象的代码: public Resend FindById (string id) { return CollRevendas.Find
(revenda => revenda.Id == id).FirstOrDefault); } -
您可以将此代码添加到问题中吗?
-
我用用于检索经销商的代码编辑了问题。
-
您是否尝试过更新检索到的对象
var parentObject=CollRevendas.Find<Revenda>(revenda => revenda.Id == id).FirstOrDefault();parentObject.Clientes.Add(newChildObject);//now update the parent object