Based on the ASP.net MVC tutorial's GenericRepository pattern (Implementing the Repository and Unit of Work Patterns in an ASP.NET MVC Application), what speaks against implementing multi tenancy as follows:
public class GenericMultiTenantRepository<TEntity> where TEntity : MultitenantEntity
{
internal SchoolContext context;
internal DbSet<TEntity> dbSet;
...
public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
query = query.Where(entity => entity.TenantId == <TenantId>); /* Like this? */
foreach (var includeProperty in includeProperties.Split
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
else
{
return query.ToList();
}
}
and MultitenantEntity just being the following:
public class MultitenantEntity {
public int TenantId {get;set;}
}
All entities now derive from MultitenantEntity and you can still program the entire app as if it was intended for just one tenant?
Am I overseeing something? Or is there a more widely accepted practice to achieve what I'm trying to do?
The same principles should be added to the insert method as well, but I omitted those changes for brevity.