Right Way to Make Relationship One To Many Using C# and Mongodb

Asked

Viewed 331 times

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; }
    }

Entity Comentário:

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 will look 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"
                    }
                  ]
     }

That’s the right way to make this relationship?

1 answer

2


That’s the right way to make this relationship?

Yes, whereas Comentario is mainly related to a Sistema. Comentario will be defined as a Sistema.

What may have been missing, if you like, is a DBRef to the author of the comment, if it is of interest to him that the author of the comment is a system user:

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

Use:

var autor = db.FollowReference<Usuario>(comentario.Autor);
  • 1

    Thanks, had not thought about the possibility of using Dbref rs.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.