[英]Multi-tenancy in EF6 with multiple schemas having the same tables
In our system it has become required to provide a multi-tenant solution, where each tenant has the same data structure.在我们的系统中,需要提供多租户解决方案,其中每个租户具有相同的数据结构。
During investigation I came across an article discussing multi-tenancy with EF4.1.在调查期间,我看到了一篇讨论 EF4.1 多租户的文章。
http://romiller.com/2011/05/23/ef-4-1-multi-tenant-with-code-first/ http://romiller.com/2011/05/23/ef-4-1-multi-tenant-with-code-first/
This looks like a sensible solution, but we would prefer to avoid multiple database contexts if possible.这看起来是一个明智的解决方案,但我们更愿意尽可能避免多个数据库上下文。
Also, we have a large number of migrations for our current single tenant solution.此外,我们为当前的单租户解决方案进行了大量迁移。 With EF6, it is possible for a migration to target a specific context and when none is supported, a default is targeted.
使用 EF6,迁移可以针对特定上下文,当不支持时,将针对默认值。
I have a couple of quesions here:我在这里有几个问题:
Any help is much appreciated!任何帮助深表感谢!
I understand this is old, however it's still widely searched topic.我知道这是旧的,但它仍然是广泛搜索的话题。
I have used the following methods successfully with having multi-tenant by schema, using Code-First or DB First using EDMX.我已经成功地使用以下方法通过模式使用代码优先或使用 EDMX 的 DB First 来实现多租户。
IDbCommandInterceptor
and include command.CommandText = command.CommandText.Replace("<unwanted-schema-here>", "<your-actual-schema>")
under all the *Executing implementations.IDbCommandInterceptor
并在所有*Executing实现下包含command.CommandText = command.CommandText.Replace("<unwanted-schema-here>", "<your-actual-schema>")
。 Then Remove and Add the Interceptor before initializing a new context. Example: Place your factory method inside a Partial class of your DbContext
.示例:将工厂方法放在
DbContext
的 Partial 类中。
Private Shared _lschema As String
Public ReadOnly Property schema As String = _lschema
Public Shared Function GetContext(Optional connString As String = Nothing) As MyContext
If connString IsNot Nothing Then
Dim conn As EntityConnection = ContextHelper.CreateConnection(Of MyContext)(connString,ByRef _lschema)
DbInterception.Remove(New SchemaInterceptor)
DbInterception.Add(New SchemaInterceptor(_lschema))
Dim ctx = New MyContext(conn, False)
ctx.Configuration.LazyLoadingEnabled = False
ctx.Configuration.AutoDetectChangesEnabled = True
Return ctx
End If
Return New MyContext()
End Function
IDbModelCacheKeyProvider
, this is used in a similar method as the example above.IDbModelCacheKeyProvider
动态构建您自己的模型,这在与上述示例类似的方法中使用。 Such as building your connection by calling a method that gets the schema of the connection and returning it.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.