Multitenancy with Entity Framework

3

I have my application, which shares the same database with all my clients.

By separating them only by a column of the Empresa_Id table, all my actions, Save, List, Edit, Delete are done by my repository.

In my repository I pass the business ID, always before executing the action. But in my Edit, as it sends the Id through the URL to return to View, I can not handle this, and others can access the data of others.

So what's flawed is this method of the repository here:

public virtual T getById(int id)
{
  return _dbSet.Find(id);
}

Any ideas to get around this problem?

I've even thought about changing my PK all to GUID, but I'm afraid my queries will be very slow (since the Entity Framework is famous for being a slow ORM compared to others).

    
asked by anonymous 13.10.2014 / 21:28

1 answer

2

If you have no way to identify just about any record of the entities in your application, something is very wrong.

In the Multi-tenant model, the key need not necessarily be composed. The error you are having is because the entity was built more or less like this:

public class Entidade
{
    [Key, Column(Order=1)]
    public int EmpresaId { get; set; }
    [Key, Column(Order=2)]
    public int EntidadeId { get; set; }
    ...
}

Sometimes I've warned you about this approach. The correct would be:

public class Entidade
{
    [Key]
    public int EntidadeId { get; set; }
    public int EmpresaId { get; set; }
    ...
}

So you can uniquely identify your records and place access verification rules on the Controller layer , or via Filters , as an example in this answer (example is for logging, but it is a basis for an authorization filter) .

Now, if really you need to use compound key in the application, you can change the request link to act as follows:

http://localhost/Entidades/Edit/1?EmpresaId=2

The method in Controller , therefore, would look like this:

public ActionResult Edit(int id, int EmpresaId) {
    ...
}
    
13.10.2014 / 23:09