Prevent duplicate registration with C#

Asked

Viewed 849 times

1

I’m having a hard time with the duplicity record. How do I so that after the user fills in the form, at the time of saving, the data is compared to what is in the database, if he has any repeated field he does not save the form data?

inserir a descrição da imagem aqui

        [HttpPost]
        public ActionResult CadastrarProspect(string prospectnome, string prospectemail, string prospectcelular, string prospecttelefone, string prospectanotacao)
        {
            //Pegar Vendedor Logado
            var model = new ProspectViewModel();

            model.Prospect.IdVendedor = VariaveisDeSessao.VendedorLogado.IdVendedor;
            model.Prospect.DsNome = prospectnome;
            model.Prospect.DsEmail = prospectemail;
            model.Prospect.DsCelular = prospectcelular.Replace("-", "").Replace(".", "").Replace("(", "").Replace(")", "").Replace(" ", "");
            model.Prospect.DsTelefone = prospecttelefone.Replace("-", "").Replace(".", "").Replace("(", "").Replace(")", "").Replace(" ", "");
            model.Prospect.DsAnotacao = prospectanotacao;

            var prospAdd = new ProspectBLL().AdicionarProspect(model.Prospect);

            if (prospAdd == 0)
            {
                return RedirectToAction("Index", "Prospect", new { mensagem = "Erro no Cadastro." });
            }
            else
            {
                return RedirectToAction("Index", "Prospect");
            }
        }
   public class ProspectBLL : BaseBLL
    {
        //Adicionar Prospect
        public long AdicionarProspect(Prospect prospect)
        {
            try
            {
                prospect.FgAtivo = true;
                prospect.FgExcluido = false;
                prospect.DtCriacao = DateTime.Now;
                prospect.DtAlteracao = DateTime.Now;
                banco.Prospect.Add(prospect);
                return banco.SaveChanges();
            }
            catch (Exception ex)
            {
                new Logger.Logger().FazerLogAsync(ex, new { Tipo = "Erro", Mensagem = "Erro ao adicionar novo vendedor" }, Logger.EnumTiposDeLog.TiposDeLog.Erro);
                return 0;
            }
        }
<div class="modal" id="myModal" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="close">&times;</button>
                <h3 class="modal-title">Novo prospect</h3>
            </div>
            <form method="post" action="/Prospect/CadastrarProspect">
                <div class="modal-body">
                    <div class="form-group">
                        <label for="nome" class="col-form-label">Nome*</label>
                        <input type="text" class="form-control" id="nomeprospect" name="prospectnome" required>
                    </div>
                    <div class="form-group">
                        <label for="email" class="col-form-label">E-mail</label>
                        <input type="text" class="form-control" id="emailprospect" name="prospectemail">
                    </div>
                    <div class="form-group">
                        <label for="celular" class="col-form-label">Celular*</label>
                        <input type="text" class="form-control" id="celularprospect" name="prospectcelular" required>
                    </div>
                    <div class="form-group">
                        <label for="telefone" class="col-form-label">Telefone</label>
                        <input type="text" class="form-control" id="telefoneprospect" name="prospecttelefone">
                    </div>
                    <div class="form-group">
                        <label for="anotacao" class="col-form-label">Anotação</label>
                        <textarea class="form-control" id="anotacaoprospect" name="prospectanotacao" rows="4" cols="50"></textarea>
                    </div>
                    <div class="form-group">
                        <label id="camposobrigatorios" class="col-form-label">*Campos obrigatórios</label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary" id="btnOK">Salvar</button>
                </div>
            </form>
        </div>
    </div>
</div>
  • 1

    Could you edit your question and add your current code? We need to see how your application model is doing to help you.

1 answer

2

Man, the way I see it, you got two options.

The first of these is to create a Constraint in the database table that makes it impossible to create duplicate records. In this case the bank itself will return an error warning that this record already exists.

Another option is to do the search before saving. You can do something like:

public long AdicionarProspect(Prospect prospect)
    {
        try
        {
            if (banco.Prospect.Any(x => x.DsNome == prospect.DsNome)) // Aqui você coloca todos os campos que não podem ser duplicados
                throw new Exception("Registro duplicado");

            prospect.FgAtivo = true;
            prospect.FgExcluido = false;
            prospect.DtCriacao = DateTime.Now;
            prospect.DtAlteracao = DateTime.Now;
            banco.Prospect.Add(prospect);
            return banco.SaveChanges();
        }
        catch (Exception ex)
        {
            new Logger.Logger().FazerLogAsync(ex, new { Tipo = "Erro", Mensagem = "Erro ao adicionar novo vendedor" }, Logger.EnumTiposDeLog.TiposDeLog.Erro);
            return 0;
        }
    }

I hope it helps you, vlw

  • This bit I put in the right BLL ? And the controller part how can I call ?

  • 1

    At first the controller does not need to change, because Exception will return 0 and display the "Registration Error" message. If you need to show differentiated messages for each type of error you can set some code and in the controller change the error message according to the code.

  • It hasn’t worked out yet... :(

Browser other questions tagged

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