具有实体框架的简单多租户Web应用程序的解决方案 [英] Solutions for a simple multi tenant web application with entity framework

查看:149
本文介绍了具有实体框架的简单多租户Web应用程序的解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个多租户Web应用程序(堆栈:MVC 4 +实体框架4.3). 我的要求非常简单:每个租户都具有相同的UI和CodeBase.

I'm developing a multi-tenant web app (stack: MVC 4 + Entity framework 4.3). My requirements are pretty simple: each tenant has the same UI and CodeBase.

在我的数据库中,我有一些带有TenantId字段的表(还有一些没有TenantId字段的表).

In my database I have some tables with a TenantId field (and other tables without).

我已经建立了一个非常简单的通用存储库:

I have set up a very simple generic repository:

public class GenericRepository<TEntity> where TEntity : class
{
    internal Database.CRMEntities context;
    internal DbSet<TEntity> dbSet;
    internal int tenantId;

    public GenericRepository(Database.CRMEntities context)
    {
        this.context = context;
        this.dbSet = context.Set<TEntity>();
        this.tenantId = 1;
    }

我希望使用"get"方法来过滤我的tenantId.我的插入,更新和删除方法也应约束适当的TenantId.

I'd like the "get" methods to filter for my tenantId. My insert, update and delete method should also constrain the appropriete TenantId.

我的实体是自动生成的POCO类.

My Entities are autogenerated POCO classes.

我已经考虑了以下解决方案:

I have considered these solutions:

1- GenericRepository应该实现一个定义TenantId的"ITenant"接口.问题是某些实体没有TenantId属性.另外,我真的不喜欢修改用于生成POCO对象的T4模板,以使其实现我的界面

1- GenericRepository should implement a "ITenant" interface that defines TenantId. Problem is that some entities haven't got the TenantId property. Also, I don't really like to modify the T4 template I use to generate POCO objects to make them implement my interface

2-反射(但是,EF当然不能将其转换为SQL语句)

2- Reflection (but of course EF can't translate it to a SQL statement)

if (typeof(TEntity).GetProperty("TenantId") != null)
            query = query.Where(x => (int)   (x.GetType().GetProperty("TenantId").GetValue(x, null)) == tenantId);

在我的情况下,您会怎么做?我愿意在必要时重新考虑我的体系结构.

What would you do in my case? I'm willing to reconsider my architecture if necessary.

谢谢, 尼古拉

推荐答案

您可以进行反射检查,然后手动创建EF可以理解的表达式树.

You can do the reflection check and then manually create an expression tree that EF can understand.

例如:

int tenantId = 5;

var tenantIdInfo = typeof(TEntity).GetProperty("TenantId");

if (tenantIdInfo != null)
{
    var entity = Expression.Parameter(typeof(TEntity), "it");

    var predicate = (Expression<Func<TEntity, bool>>)Expression.Lambda(
        Expression.Equal(
            Expression.MakeMemberAccess(entity, tenantIdInfo),
            Expression.Constant(tenantId, typeof(int))),
        entity);

    query = query.Where(predicate);
}

这篇关于具有实体框架的简单多租户Web应用程序的解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆