Pass fixed value to repository

1

I have my repository, with method of adding

public virtual T Adiciona(T entity)
{
  _dbSet.Add(entity);
  return entity;
}

Not if it is possible,

All my classes inherit from "ModelBase"

  public class ModelBase
  {
    [Key]
    public int Id { get; set; }
    public int EmpresaId { get; set; }
  }

This companyId is a user property, which is the company that it is linked to

I want to write all my models that inherit from modelbase, I want to pass the company id already

Any ideas how to do this?

    
asked by anonymous 29.08.2014 / 17:54

1 answer

1

Yes. In fact just change to the following:

public virtual T Adiciona(T entity)
{
    var empresaId = LoggedUserHelper.GetEmpresaUsuario(User);
    var objetoEmpresa = new Empresa { EmpresaId = empresaId };
    contexto.Empresas.Attach(objetoEmpresa);
    entity.Empresa = objetoEmpresa;
    contexto.Set<T>.Add(entity);
    return entity;
}

This LoggedUserHelper is a static class something like this:

namespace SeuProjeto.Helpers {
    public static class LoggedUserHelper {
        private static SeuProjetoContext contexto = new SeuProjetoContext();

        public static int GetEmpresaUsuario {
            return contexto.Usuarios.SingleOrDefault(u => u.Nome == User.Identity.Name).UsuarioId;
        }
    }
}

I'm assuming you use either FormsAuthentication , or ASP.NET Membership, or ASP.NET Identity.

    
29.08.2014 / 20:02