Validate Business Rule

0

I am using this example tutorial Data Repositories to create a layered crud with the Entity Framework with Code First.

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

How do I create this in my UserBLL?

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

  • Or should I create a new method just to get the 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 USERIODAL

using Model;
using DAL.Repositorio;

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

    }   
}

class model User NOTE: I did not apply OO yet just an 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; }
                }

        }
    }
    
asked by anonymous 05.04.2017 / 04:07

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 a data annotation

    //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;
    }
}
    
05.04.2017 / 17:05