我需要的大部分答案都在这里找到:
http://romiller.com/2011/05/23/ef-4-1-multi-tenant-with-code-first/
public partial class MyDBContext
{
public MyDBContext() : base() { }
private MyDBContext(DbConnection connection, DbCompiledModel model) : base(connection, model, contextOwnsConnection: false) { }
private static ConcurrentDictionary<Tuple<string, string>, DbCompiledModel> modelCache
= new ConcurrentDictionary<Tuple<string, string>, DbCompiledModel>();
public static MyDBContext Create(string tenantSchema, DbConnection connection)
{
var compiledModel = modelCache.GetOrAdd
(
Tuple.Create(connection.ConnectionString, tenantSchema),
t =>
{
var builder = new DbModelBuilder();
builder.Conventions.Remove<IncludeMetadataConvention>();
builder.Entity<Location>().ToTable("Locations", tenantSchema);
builder.Entity<User>().ToTable("Users", tenantSchema);
var model = builder.Build(connection);
return model.Compile();
}
);
var context = new FmsDBContext(connection, compiledModel);
if( !string.IsNullOrEmpty( tenantSchema ) && !tenantSchema.Equals( "dbo", StringComparison.OrdinalIgnoreCase ) )
{
var objectContext = ( (IObjectContextAdapter)context ).ObjectContext;
objectContext.Connection.Open();
var currentUser = objectContext.ExecuteStoreQuery<UserContext>( "SELECT CURRENT_USER AS Name", null ).FirstOrDefault();
if( currentUser.Name.Equals( tenantSchema, StringComparison.OrdinalIgnoreCase ) )
{
var executeAs = string.Format( "REVERT; EXECUTE AS User = '{0}';", tenantSchema );
objectContext.ExecuteStoreCommand( executeAs );
}
}
return context;
}
}
然后你可以像这样访问 Schema 的信息:
using (var db = MyDBContext.Create( schemaName, dbConn ))
{
// ...
}
然而,这绕过了实际使用数据库用户。我仍在研究如何使用数据库用户的上下文,而不仅仅是指定模式名称。
更新:
我终于解决了这里的最后一个障碍。关键是以下代码:
if( !string.IsNullOrEmpty( tenantSchema ) && !tenantSchema.Equals( "dbo", StringComparison.OrdinalIgnoreCase ) )
{
var objectContext = ( (IObjectContextAdapter)context ).ObjectContext;
objectContext.Connection.Open();
var currentUser = objectContext.ExecuteStoreQuery<UserContext>( "SELECT CURRENT_USER AS Name", null ).FirstOrDefault();
if( currentUser.Name.Equals( tenantSchema, StringComparison.OrdinalIgnoreCase ) )
{
var executeAs = string.Format( "REVERT; EXECUTE AS User = '{0}';", tenantSchema );
objectContext.ExecuteStoreCommand( executeAs );
}
}
EXECUTE AS 命令在用于执行稍后的 linq to entity 命令之前在连接上发出。只要连接保持打开状态,用户的上下文就会保持不变。在我的数据库中,租户的架构名称和用户名是相同的。
多次更改用户的执行上下文会导致错误,因此使用快速查询来确定当前的用户上下文。需要一个小型实体类来使用连接检索信息:
private class UserContext
{
public string Name { get; set; }
}