Correct way to make one-to-many relationship using C # and MongoDB

4

I have two entities, Sistema and Comentario where a system can have several comments:

   public class Sistema
    {
        public ObjectId Id { get; set; }
        [BsonElement("SistemaId")]
        public int SistemaId { get; set; }
        [BsonElement("Key")]
        public int Key { get; set; }

        [BsonElement("Comentarios")]
        public List<Comentario> Comentarios { get; set; }
    }

Comment Entity:

public class Comentario
{
    public ObjectId Id { get; set; }
    public string Mensagem { get; set; }
    public DateTime DataCriacao { get; set; }

}

The idea is that the end result looks like this:

{
       _id: "3213",
       SistemaId: 11701,
       Key: 01
       comentarios: [
                    {
                      _Id: "1",
                      Mensagem: "Comentário 1",
                      DataCriacao: "2016-07-05"
                    },
                    {
                      _Id: "2",
                      Mensagem: "Comentário 2",
                      DataCriacao: "2016-07-06"
                    }
                  ]
     }

Is this the right way to do this?

    
asked by anonymous 05.07.2016 / 14:40

1 answer

2
  

Is this the right way to do this?

Yes, considering that Comentario is mainly related to Sistema . Comentario will be defined as a Sistema subdocument.

What you may have missed, if you like, is DBRef for the comment author, if it is in your interest for the comment author to be a user of the system:

public class Comentario
{
    public ObjectId Id { get; set; }
    public string Mensagem { get; set; }
    public DateTime DataCriacao { get; set; }
    public DBRef Autor { get; set; }
}

Usage:

var autor = db.FollowReference<Usuario>(comentario.Autor);
    
05.07.2016 / 16:06