为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用 C# 在 MongoDB 中的对象的项目数组中包含一个新项目?

如何使用 C# 在 MongoDB 中的对象的项目数组中包含一个新项目?

C#
斯蒂芬大帝 2022-12-31 12:51:58
如何使用 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;        }    }}但是,如何才能在已在 MongoDB 中注册的父对象 (Revenda) 中只包含一个新的子对象 (RevendaCliente)?我正在使用以下环境: -Microsoft.AspNetCore.App (2.1.1) -MongoDB.Driver (2.8.0)
查看完整描述

2 回答

?
慕的地10843

TA贡献1785条经验 获得超8个赞

(正如我在评论中提到的)您的问题看起来很简单,因为在 MongoDB 中,层次结构中的相关对象是同一文档的一部分,因此您需要更新内存中的对象并对其进行更新。


var parentObject=CollRevendas.Find<Revenda>(revenda => revenda.Id == id).FirstOrDefault();

parentObject.Clientes.Add(newChildObject);

//now update the parent object


查看完整回答
反对 回复 2022-12-31
?
茅侃侃

TA贡献1842条经验 获得超22个赞

对我有用的代码:(在 Aarif 的支持下解决)


public bool AddRevendaCliente(string revendaId, RevendaCliente requestRevendaClient)

{

    try

    {

        var filter = Builders<Revenda>.Filter.Eq(s => s.Id, revendaId);


        // Get a reference to the parent parent "Revenda"

        var parentObject = CollRevendas.Find<Revenda>(filter).FirstOrDefault();

        parentObject.Clientes.Add(requestRevendaClient);


        // Update the parent object "Revenda"

        var result = CollRevendas.ReplaceOneAsync(filter, parentObject);

    }

    catch (Exception ex)

    {

        throw;

    }            

    return true;

}


查看完整回答
反对 回复 2022-12-31
  • 2 回答
  • 0 关注
  • 147 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号