Linking Users to Companies and Bringing User-related Records Using ASP.NET Identity and Entity Framework

1

I have records in the database (for example, clients), and all records have a EmpresaID identifier. I'm using identity with entity framework to authenticate. In the user's registry I have an identifier "CompanyId".

I would like to know how to bring only the records that EmpresaId of the client is equal to EmpresaId of the 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 it 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());
}
    
asked by anonymous 17.08.2016 / 22:42

1 answer

0

Ideally, your Usuario has the EmpresaId property as follows:

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

So you retrieve 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 simplified your code a lot. You do not have to instantiate empresa and usuario because they can be obtained from other places in the framework .

This here:

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

Does not generate a list: it generates an object of 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());
    
17.08.2016 / 23:09