How to resolve the error: The best overloaded method match for

1

Following the templates this question when I have the following command:

"The best overloaded method match for some invalid arguments"

Controller

public ActionResult Novo()
    {
        ViewBag.Nacionalidade = new SelectList(db.Util.Where(u => u.tipo == 14), "id", "nome");

        var candidato = new CandidatoViewModel();

        return View(candidato);
    }

    [HttpPost]
    public ActionResult Novo(CandidatoViewModel candidato)
    {
        if (ModelState.IsValid) 
        {         
            db.Candidato.Add(candidato); // erro esta aqui

            db.SaveChanges();
            return RedirectToAction("VerCandidato", new { id = candidato.id });            
        }

        ViewBag.Nacionalidade = new SelectList(db.Util.Where(u => u.tipo == 14), "id", "nome", candidato.id_nacionalidade);

        return View(candidato);
    }
    
asked by anonymous 17.11.2015 / 17:19

1 answer

7

Well, it will not work, of course. You are trying to add CandidatoViewModel to the context, but a ViewModel is not context-mapped by definition.

The correct thing would be for you to do:

[HttpPost]
public ActionResult Novo(CandidatoViewModel candidato)
{
    if (ModelState.IsValid) 
    {         
        Candidato candidatoModel = candidato;
        db.Candidato.Add(candidatoModel); 

        db.SaveChanges();
        return RedirectToAction("VerCandidato", new { id = candidato.id });            
    }

    ViewBag.Nacionalidade = new SelectList(db.Util.Where(u => u.tipo == 14), "id", "nome", candidato.id_nacionalidade);

    return View(candidato);
}

This:

Candidato candidatoModel = candidato;

This is valid if you implement an implicit operator , as follows:

public class Candidato
{
    // Aqui vão as declarações normais do Model

    public static implicit operator Candidato(CandidatoViewModel c)
    {
        return new Candidato {
            Nome = c.Nome,
            Idade = c.Idade,
            ...
        };
    }
}

There are still those who use AutoMapper instead of using an implicit operator, but optically speaking, I'm not much of a fan.

    
17.11.2015 / 17:32