Is it correct in MVC to access data within the model?

3

In a C # MVC project, is it okay to access data within the model ? For example:

public class Cliente
{
    public int Id { get; set; }

    public string Nome { get; set; }

    //outros atributos...

    public void Inserir(){
        Cliente c = new Cliente();

        //Outras ações

        DaoCliente dao = new DaoCliente();
        dao.InserirCliente(c);
    }
}

Is that correct?

    
asked by anonymous 26.10.2017 / 16:16

2 answers

4

In general everything that refers to the data must be done in the model, although indirectly. Any operations that manipulate the data should be in the model.

Then the method of inserting that data must be placed in the same model. And you can put the detail out of it, as was done in this example.

I guess the question is whether the controller should do the whole implementation of the insert and should not generally.

Each with its own responsibility. The controller should tell you what to do and not how to do it.

I had not paid attention initially, but the Cliente c = new Cliente(); line does not do what it imagines. You are creating another object within the object you are manipulating. This should not be done unless you have a reason to have a new customer inside the client, which is highly unlikely.

It is not this client that you should use to write the template, it is this .

I find it odd to create a new client in invalid state .

And I do not think this DAO is well built. I actually question the use of specific DAO so, but that's another matter.

    
26.10.2017 / 16:24
4

Just a note, if you have a method inside the class itself, you do not need to instantiate a new object:

public class Cliente
{
    public int Id { get; set; }

    public string Nome { get; set; }

    //outros atributos...

    public void Inserir(){
        //Outras ações

        DaoCliente dao = new DaoCliente();
       this.Id = dao.InserirCliente(this); //Já atribui a Id que foi inserida ao objeto atual
    }
}

But I would use a static method:

public class Cliente
{
    public int Id { get; set; }

    public string Nome { get; set; }

    //outros atributos...

    public static int Inserir(Cliente c)
    {
        //Outras ações

        DaoCliente dao = new DaoCliente();
        return dao.InserirCliente(c);
    }
}

or

public class Cliente
{
    public int Id { get; set; }

    public string Nome { get; set; }

    //outros atributos...

    public static int Inserir(string nome)
    {
        Cliente c = new Cliente();
        c.Nome = nome;
        //Outras ações

        DaoCliente dao = new DaoCliente();
        return dao.InserirCliente(c); //retorna a id que foi inserida
    }
}

can still be overloaded.

  

I know it's not the answer to what was asked, but it's just an observation that I think is valid. I hope not to receive negatives for this =]

    
26.10.2017 / 17:28