Pass fixed value to Repository

Asked

Viewed 62 times

1

I have my Repository, with add method

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

Not if it’s possible,

All my classes inherit from "Modelbase"

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

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

I want to record all my models that inherit from modelbase, I want to pass the company id now

Any idea how to do that?

1 answer

1


Yes. Actually 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;
}

That one LoggedUserHelper is a static class more or less 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 guessing you use either FormsAuthentication, or ASP.NET Membership, or ASP.NET Identity.

  • Gypsy, because I am receiving a generic, he does not even accept that I pass "Entity. Property = value"

  • @Rod Declare your generic as where T: ModelBase

Browser other questions tagged

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