Validate Business Rule

Asked

Viewed 283 times

0

I’m using this sample tutorial Data repository to create a layered crud with Entity Framework with Code First.

My question would be how to validate a business rule where a user with already existing login in the database cannot be registered.

How should I create this in my Usersbll?

  • a method validatCadastroUsuario(User u) but call the method Get of my repository (User), but how do I check if something has returned or if it is empty ?

  • or I should create a new method just to search for logins?

The Repository that I used: ->

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Data.Entity;
using Repositorio.DAL.Contexto;

namespace Repositorio.DAL.Repositorios.Base
{
    public abstract class Repositorio<TEntity> : IDisposable,
       IRepositorio<TEntity> where TEntity : class
    {
        BancoContexto ctx = new BancoContexto();
        public IQueryable<TEntity> GetAll()
        {
            return ctx.Set<TEntity>();
        }

        public IQueryable<TEntity> Get(Func<TEntity, bool> predicate)
        {
            return GetAll().Where(predicate).AsQueryable();
        }

        public TEntity Find(params object[] key)
        {
            return ctx.Set<TEntity>().Find(key);
        }

        public void Atualizar(TEntity obj)
        {
            ctx.Entry(obj).State = EntityState.Modified;
        }

        public void SalvarTodos()
        {
            ctx.SaveChanges();
        }

        public void Adicionar(TEntity obj)
        {
            ctx.Set<TEntity>().Add(obj);
        }

        public void Excluir(Func<TEntity, bool> predicate)
        {
            ctx.Set<TEntity>()
                .Where(predicate).ToList()
                .ForEach(del => ctx.Set<TEntity>().Remove(del));
        }

        public void Dispose()
        {
            ctx.Dispose();
        }
    }
}

In my class USER

using Model;
using DAL.Repositorio;

namespace DAL
{ 
    public class UsuarioDAL : Repositorio<Usuario>
    {

    }   
}

model class User NOTE: I haven’t applied OO yet just one example!

  namespace Model
    {
        [Table("Usuario", Schema = "public")]
        public class Usuario : Pessoa
        {
                [Key]
                public int Codigo { get; set; }
                private string nome;

                [Required(AllowEmptyStrings = false, ErrorMessage = "Login deve ser preenchido!")]
                [StringLength(50)]
                [Index("Ix_UsuarioLogin", IsUnique = true)]
                public string Login { get; set; }

                [Range(0, 1)]
                public int Status { get; set; }

                [Required(AllowEmptyStrings = false, ErrorMessage = "Nome deve ser preenchido")]
                [StringLength(100)]
                public string Nome
                {
                    get { return nome; }
                    set { nome = value; }
                }

        }
    }

1 answer

0


public class Usuario : Pessoa
    {
            [Key]
            public int Codigo { get; set; }
            private string nome;
            [LoginDisponivel(ErrorMessage = "Erro. Este Login já encontra-se em uso. Tente outro.")]   
            [Required(AllowEmptyStrings = false, ErrorMessage = "Login deve ser preenchido!")]
            [StringLength(50)]
            [Index("Ix_UsuarioLogin", IsUnique = true)]
            public string Login { get; set; }

            [Range(0, 1)]
            public int Status { get; set; }

            [Required(AllowEmptyStrings = false, ErrorMessage = "Nome deve ser preenchido")]
            [StringLength(100)]
            public string Nome
            {
                get { return nome; }
                set { nome = value; }
            }

    }

creating an Annotation data

    //Regra 1) Para criar uma validação customizada,
        //devemos herdar ValidationAttribute
        public class LoginDisponivel : ValidationAttribute
        {
            //Para programarmos a regra de validação, devemos
            //sobrescrever (override) do método IsValid()
            public override bool IsValid(object value)
            {
                try
                {
                    //resgatando o valor do campo sob o qual a validação foi aplicada..
                    string Login = (string) value;

                    UsuarioDal d = new UsuarioDal(); //persistencia..
                    return ! d.HasLogin(Login); //se login não existe?
                }
                catch
                {
                    return false;
                }
            }
    }

creating method to validate login

public bool HasLogin(string Login)
{

    using(Conexao Con = new Conexao())
    {
        return Con.Usuario
                .Where(u => u.Login.Equals(Login))
                .Count() > 0;
    }
}
  • Sure I understood your logic, only this part I’m doubting Return ! d. Haslogin(Login); //if login does not exist? What does it return if it doesn’t exist? Something else couldn’t just create this hasLogin method and in my User check if the return is greater than 0 ? what to create a new class? Thank you

  • can reverse logic was only an example at the end ai if login exists it will give false

  • Thank you, just another question I see that the Gypsy user speaks on their topics that should not use the Repository, so I am developing wrong with my repository?

  • only thing I found different I do not do in your code is you validate login in the model that will be persisted I would do in a model that when it goes through the control would already validate it , while Pattern repository has some ways to do more ta cool yes

Browser other questions tagged

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