Validation when editing existing registration?

Asked

Viewed 150 times

0

I have the following problem: I am touching the part of controller of my system on the part of editing registrations and it does the following check, if I enter an existing code, it displays a alert.

ModelState.AddModelError("UserNotFound", 
                         "Este Paciente já está cadastrado!: ");

And I wanted it to be time to display the alert to let him know what the ID of patient that was registered with the data that I made the following change.

ModelState.AddModelError("UserNotFound",
                         "Este Paciente já está cadastrado!: " + obj.CadastroId);

Only when I use the obj.CadastroId he is exhibiting the ID of patient I am editing. In short, when the alert appears, display the ID of patient that has already been registered with that data.

Could someone help me with this? , I left on this link the method I’m using on controller.

Repository:

public bool pacienteExiste(string numero_protuario)  
{  
    Cadastro cadastro = Db.Cadastros
         .FirstOrDefault(c => c.pront == numero_protuario);  
    return cadastro != null;  
} 

Service:

public bool pacienteExiste(string numero_protuario)
{
    return _cadastroRepository.pacienteExiste(numero_protuario);
}        

Controller:

[HttpPost]  
public ActionResult EditarCadastro(Cadastro obj)  
{  
    if (_cadastroService.pacienteExiste(obj.pront))  
    {  
        ModelState.AddModelError("UserNotFound", 
                "Este Paciente já está cadastrado!: " + obj.CadastroId);  
        return View(obj);  
    }  
    if ((obj.pront != null) || (obj.inpac != null) || (obj.dtnasc != null))  
    {  
        _cadastroService.Update(obj);  
    }  
    else  
    {  
        return RedirectToAction("Index", "Cadastro");  
    }  
    return RedirectToAction("Index", "Cadastro");  
}  
  • Why not put the code right here? In fact, also put the method code _cadastroService.pacienteExiste

  • @jbueno public bool patientExiste(string numero_protuario) { Registration = Db.Cadastros.Firstordefault(c => c.pront == numero_protuario); Return registration != null; }

  • Client at [Edit] and put the code in the question.

  • @jbueno put there, but I can’t edit to make visible

  • Select the code and click Ctrl + k

  • @jbueno Pronto!

Show 1 more comment

2 answers

0


It is only necessary to search this record in the bank to return his information.

Take advantage of the method that searches the record to validate, removing the need to use _cadastroService.pacienteExiste(obj.pront). So the query only needs to be made once in the bank.

In fact, I realized that a service making a middle ground (why all this??) so I’ll follow your pattern.

Repository:

public Cadastro BuscaPacientePeloProtuario(string numero_protuario)
{
    return Db.Cadastros.FirstOrDefault(c => c.pront == numero_protuario);  
}

Service:

public Cadastro BuscaPacientePeloProtuario(string numero_protuario)
{
    return _cadastroRepository.BuscaPacientePeloProtuario(numero_protuario);
}

Controller

[HttpPost]  
public ActionResult EditarCadastro(Cadastro obj)  
{  
    var existente = _cadastroService.BuscaPacientePeloProtuario(obj.pront);

    if (existente != null)
    {             
        ModelState.AddModelError("UserNotFound", "Este Paciente já está cadastrado!: " + existente.CadastroId);

        return View(obj);  
    }  

    if ((obj.pront != null) || (obj.inpac != null) || (obj.dtnasc != null))  
    {  
        _cadastroService.Update(obj);  
    }  
    else  
    {  
        return RedirectToAction("Index", "Cadastro");  
    }  

    return RedirectToAction("Index", "Cadastro");  
}  

0

Thinking of a more elegant code I would recommend you to use the concept Tell Don’t Ask

Ta, but what does that help your problem? By improving the designe you can return the error encapsulating your user’s validation logic. See an example below of how your code could be written, just adapt its structure, variable names and patterns:

 enum Status
{
    Sucesso,
    Falha
}

interface IErros
{
    void AdicionarErro(IErros erro);
}

interface IResultado
{
    Status Status { get; }
    IErros Erros { get; }
}

class Falha : IResultado
{
    public IErros Erros { get; private set; }

    public Status Status { get { return Status.Falha; } }

    public IResultado AdicionarErro(string mensagem)
    {
        // adiciona o erro
        return this;
    }
}

class Sucesso : IResultado
{
    public IErros Erros { get; private set; }

    public Status Status { get { return Status.Sucesso; } }
}

class Cadastro
{
    public int Id { get; set; }
    public string Nome { get; set; }
    public string NumeroProntuario { get; set; }
    public DateTime DataNascimento { get; set; }
}

class Db
{
    public static IEnumerable<Cadastro> Cadastros { get; set; }
}

class CadastroService
{
    public IResultado SalvarPaciente(Cadastro dadosCadastrais)
    {
        Cadastro cadastro = Db.Cadastros
             .FirstOrDefault(c => c.NumeroProntuario == dadosCadastrais.NumeroProntuario);
        if (cadastro != null)
            return new Falha().AdicionarErro("Já foi cadastrado um paciente com os mesmos dados cadastrais, Id: " + cadastro.Id);
        return new Sucesso();
    }
}

I made a small mock for db so I didn’t have to generate the EF class and context. But note that instead of returning a bool, you encapsulate the logic of your error and take responsibility of the web and can access in your controller as follows:

    public IActionResult EditarCadastro(Cadastro obj)
    {
        var resultado = _cadastroService.SalvarPaciente(obj);
        if (resultado.Status == Status.Falha)
            ModelState.AddModelError(resultado.Erros.First());

        // faz o restando da lógica
    }

With this we obtain a better elaborated design and all the complexity of the validations encapsulated in the service.

Browser other questions tagged

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