Linking Users to Businesses and bringing related records to the User’s company using ASP.NET Identity and Entity Framework

Asked

Viewed 95 times

1

I have records in the database (example, clients), and in all records have an identifier EmpresaID. I’m using identity with Entity framework to authenticate. In the user’s registration I have an identifier "Empresaid".

I wonder how do I bring only the records that the EmpresaId the customer is equal to EmpresaId user in the code below:

public ActionResult Index()
{
    Empresa empresa = new Empresa();
    RegisterViewModel usuario = new RegisterViewModel();
    var exames = db.Exames.Include(p => p.Empresa);

    return View(db.Exames.ToList());
}

Currently brings all the records:

public ActionResult Index()
{
    Empresa empresa = new Empresa();
    RegisterViewModel usuario = new RegisterViewModel();
    var exames = db.Exames.Include(p => p.Empresa);

    return View(db.Exames.ToList());
}

1 answer

0

The ideal is that your Usuario own the property EmpresaId as follows:

public class Usuario : IdentityUser
{
    public int EmpresaId { get; set; }
    public virtual Empresa Empresa { get; set; }
}

Thus, you recover your user information as follows:

var userId = User.Identity.GetUserId();
var meuUsuario = db.Set<Usuario>().FirstOrDefault(u => u.Id == userId);

Putting it all together:

public ActionResult Index()
{
    //var empresa = new Empresa();
    //var usuario = new RegisterViewModel();
    var userId = User.Identity.GetUserId();
    var meuUsuario = db.Set<Usuario>().FirstOrDefault(u => u.Id == userId);
    var exames = db.Exames.Include(p => p.Empresa).Where(e => e.EmpresaId == meuUsuario.EmpresaId);

    return View(exames.ToList());
}

Note that I have greatly simplified your code. No need to instantiate empresa and usuario because they can be obtained from other places of framework.

This here:

var exames = db.Exames.Include(p => p.Empresa).Where(e => e.EmpresaId == meuUsuario.EmpresaId);

Does not generate a list: generates an object of the type IQueryable<Exame>, that is, an object of a query that has not yet been executed.

The query is executed only here, in the call to .ToList():

    return View(exames.ToList());

Browser other questions tagged

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