ICollectionobject - how to create and use objects within the collection

0

I'm working on a project using MVC5 and EntityFramwork 6. I followed a tutorial to create a database from my templates.

Example of a template:

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 read, I have to create a Add() function, but I do not understand where.

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

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; }
}
    
asked by anonymous 13.12.2016 / 18:00

2 answers

2
  

How do I now add a comment to ICollection Comments?

Assuming this comment is done at the code-only level, you can add Comment through your 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 the most basic insertion is possible, but we're talking about an ASP.NET MVC system and so this comment will come from the screen through a form submitted by POST .

Considering that you have 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 Controller that will receive the comment like this:

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);
}
    
15.02.2017 / 17:11
-1

The comment class needs to have a change, you will need to make a 1-n relation from side to comment, and you should put the side in the comment, and to add a comment to the side you should add it this way.

I recommend reading the MSDN documentation that 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; }
    }
    
13.12.2016 / 18:15