【问题标题】:Is it ok to implement multi tenancy solely in a GenericRepository?可以仅在 GenericRepository 中实现多租户吗?
【发布时间】:2013-10-31 20:42:25
【问题描述】:

基于 ASP.net MVC 教程的 GenericRepository 模式 (Implementing the Repository and Unit of Work Patterns in an ASP.NET MVC Application),反对实现多租户的原因如下:

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();
        }
    }

而 MultitenantEntity 只是以下内容:

public class MultitenantEntity {
    public int TenantId {get;set;}
}

所有实体现在都派生自 MultitenantEntity,您仍然可以对整个应用程序进行编程,就好像它只针对一个租户一样?

我在监督什么吗?或者是否有更广泛接受的做法来实现我想要做的事情?

同样的原则也应该添加到 insert 方法中,但为简洁起见,我省略了这些更改。

【问题讨论】:

    标签: c# asp.net-mvc entity-framework asp.net-mvc-4


    【解决方案1】:

    我在监督什么吗?

    不,基本上就是这样,如果您希望一个实体仅由一个“租户”拥有。我目前正在研发一个更通用的框架,允许将权限分配给每个实体和存储库,为单个用户和用户组实现 CRUD 和其他权限。我找不到任何现有的付费或免费图书馆来执行此操作。

    请记住,在插入或更新时,您必须检查相关实体的 overposting / mass assignment,恶意用户可以在其中更改所发布的关键字段(如 ID)。

    如果您不这样做,有人可以调用Update(TEntity entity),其中entity 可由当前登录的用户写入,但entity.RelatedEntity 实际上属于其他人。

    当然,在您的情况下,您只想抽象与多租户相关的代码,因此您的 Get() 变为:

    public override virtual IEnumerable<TEntity> Get(
        Expression<Func<TEntity, bool>> filter = null,
        Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
        string includeProperties = "")
    {
        return base.Get(filter, orderBy, includeProperties)
                   .Where(entity => entity.TenantId == _tenantID);
    }
    

    【讨论】:

    猜你喜欢
    • 2018-11-14
    • 1970-01-01
    • 1970-01-01
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-05
    相关资源
    最近更新 更多