Icollection<Object> - how to create and use objects within the collection

Asked

Viewed 160 times

0

I am working on a project using MVC5 and Entityframwork 6. I followed a tutorial to create a database from my templates.

Example of a model:

public class Side
{

    public Side()
    {

    }

    public int ID { get; set; }
    public ICollection<Comment> Comments { get; set; }

    public int Content { get; set; }
}

How do I now add a comment to ICollection<Comment> Comments?

From what I’ve been reading, I have to create a function Add(), but I don’t understand where.

I also wanted to know how this works at the level of the database, how are the comments added to the database? (I have a table for Comment and Side) and I have the Comment thus defined:

public class Comment
{
    public Comment()
    {

    }

    public string Content { get; set; }
    public int ID { get; set; }
    public int AuthorID { get; set; }
    public DateTime DatePublished { get; set; }
    public DateTime DateEdited { get; set; }
    public bool edited { get; set; }
    public int VotesUp { get; set; }
    public int VotesDown { get; set; }
}

2 answers

2


How do I add a comment to Icollection Comments?

Assuming this comment is made at code level only, you can add a Comment through his Controller as follows:

var contexto = new MeuSistemaContext();
// Vamos primeiro trazer um Side qualquer
var side = db.Sides.FirstOrDefault(); // Aqui estou trazendo o primeiro Side disponível na base de dados

// Vamos agora criar um novo Comment
var novoComment = new Comment 
{
    Content = "Oi, eu sou um comentário",
    DatePublished = DateTime.Now,
    DateEdited = DateTime.Now,
    edited = False,
    VotesUp = 0,
    VotesDown = 0,
    Side = side // Esta é a parte mais importante. Aqui faço a referência entre Side e o novo Comment
};

// Agora adiciono o novo objeto ao contexto
db.Comments.Add(novoComment); // Você não precisa implementar este método Add(). Ele já existe em DbContext.
                              // Você só precisa adicionar uma referência a System.Data.Entity no seu código para usar.
db.SaveChanges(); // Aqui salvamos todas as alterações de contexto. 

I also wanted to know how this works at the database level, how are the comments added to the database?

The above example summarizes how is the most basic insertion possible, but we are talking about a system in ASP.NET MVC and therefore this comment will come from the screen through a form sent by POST.

Whereas you’ve put together a form like this:

@using (Html.BeginForm())
{
    @Html.HiddenFor(model => model.SideID)
    @Html.HiddenFor(model => model.AuthorID)
    @Html.TextAreaFor(model => model.Content)
}

And a method in the Controller who will receive the comment so:

public ActionResult AdicionarComentario(Comment comment)
{ ... }

The logic to be implemented is very similar to the example I put above, ie:

public ActionResult AdicionarComentario(Comment comment)
{
    if (ModelState.IsValid) // Aqui ocorre a validação dos dados
    {
        db.Comments.Add(comment); // Aqui, a adição do registro ao contexto
        db.SaveChanges(); // Aqui efetivamente ocorre a persistência dos dados
        return RedirectToAction("Index");
    }

    // Se o código falhar na validação, ocorrerá a linha abaixo.
    return View(comment);
}
  • 1

    Thank you, very complete your reply!

-1

The comment class needs to have a change, you will need to do 1-n side ratio for comment, and should put the side in the comment, and to add a comment to the side you should add this way.

I recommend reading the MSDN documentation which is very explanatory on the subject.

msdn Icollection

public class Program
    {
        static void Main(string[] args)
        {
             var side = new Side();
             side.Comments.add(new Comment());
        }
    }

 public class Comment
    {
        public Comment()
        {

        }

        public string Content { get; set; }
        public int ID { get; set; }
        public int Side_ID { get; set; }
        public int AuthorID { get; set; }
        public DateTime DatePublished { get; set; }
        public DateTime DateEdited { get; set; }
        public bool edited { get; set; }
        public int VotesUp { get; set; }
        public int VotesDown { get; set; }

        public virtual Side Side { get; set; }

    }

 public class Side
    {

        public Side()
        {            
        }

        public int ID { get; set; }
        public ICollection<Comment> Comments { get; set; }

        public int Content { get; set; }
    }
  • side.Comments.add(new Comment(); o add() is not implemented

  • Check that the using are correct. using System.Collections.Generic

  • were correct, but I decided to opt for another approach

Browser other questions tagged

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