简体   繁体   English

Asp.net 在现有解决方案上的多租户实施

[英]Asp.net Multi Tenancy implementation on existing solution

I have an asp.net MVC solution, Entity Framework code first, which has dozens of database tables all designed around a single company using the solution.我有一个 asp.net MVC 解决方案,首先是实体框架代码,它有几十个数据库表,都是围绕使用该解决方案的一家公司设计的。

The requirement has come up to allow multiple companies to use the solution, so what we have done is add "CompanyID" as a column to all database tables and set a default value.要求允许多家公司使用该解决方案,因此我们所做的是将“CompanyID”作为列添加到所有数据库表并设置默认值。 There is a company table with the various company names and CompanyID's.有一个包含各种公司名称和 CompanyID 的公司表。 On login the user selects the company they are logging in as which stores the CompanyID in the session.登录时,用户选择他们正在登录的公司,该公司将 CompanyID 存储在 session 中。

At the moment every Entity Framework call now has to be updated to include the CompanyID, for example when selecting Employees I am doing:目前,现在必须更新每个实体框架调用以包含 CompanyID,例如在选择我正在做的员工时:

List<Employee> employees = db.Employees.Where(x => x.CompanyID = Session.CompanyID).ToList();

As you can see it will be tedious to do this on thousands of calls to the db.如您所见,在对数据库的数千次调用中执行此操作会很乏味。 Any update, save, and fetch has to change.任何更新、保存和获取都必须更改。

Surely I am doing it the long way and there is a way at runtime, globally to append all DB calls to include the CompanyID stored in the logged in users Session?当然我正在做很长的路要走,并且在运行时有一种方法,全局到 append 所有数据库调用都包括存储在登录用户 Session 中的 CompanyID? Something that dynamically appends the CompanyID when fetching values or storing etc?在获取值或存储等时动态附加 CompanyID 的东西? Perhaps a package I can use to do this task at runtime?也许我可以使用 package 在运行时执行此任务?

In my opinion, there is no need to add CompanyID to EVERY table in the database.在我看来,没有必要将CompanyID添加到数据库中的每个表中。 I would select just "root" tables/entities for that.我会 select 只是“根”表/实体。 For example, Employee or Department clearly sounds like a many-to-one relationship with a company - so adding CompanyID there sounds right.例如, EmployeeDepartment显然听起来像是与公司的多对一关系 - 因此在此处添加CompanyID听起来是正确的。 But, for example, EmployeeEquipment which is a many-to-one relationship with Employee does not have to have CompanyID column since it can be filtered by the joined Employee table.但是,例如,与EmployeeEquipment是多对一关系的Employee不必具有CompanyID列,因为它可以被连接的Employee表过滤。

Regarding your request to filter by CompanyID globally, I'm not aware of anything that can do that per request.关于您在全球范围内按 CompanyID 过滤的请求,我不知道每个请求都可以做到这一点。 There are global filters for Entity Framework, but I'm not sure how you can apply them per-request.实体框架有全局过滤器,但我不确定如何按请求应用它们。 Take a look on.HasQueryFilter() during model creation if you are using Entity Framework Core.如果您使用的是 Entity Framework Core,请在创建 model 期间查看.HasQueryFilter()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM