每个用户将拥有一个数据库。这意味着您需要在查询数据库之前更改连接字符串。使用 CodeFluent 实体,您可以在运行时更改连接字符串:
CodeFluentContext context = CodeFluentContext.Get(MyApp.Constants.MyAppStoreName);
CodeFluentPersistence persistence = context.Persistence;
persistence.ConnectionString = GetCurrentTenantConnectionString();
var products = ProductCollection.LoadAll();
或者您可以创建一个自定义CodeFluentPersistence
:
public class MultiTenantPersistence : CodeFluentPersistence
{
public MultiTenantPersistence(CodeFluentContext context) : base(context)
{
}
public override string ConnectionString
{
get
{
return GetCurrentTenantConnectionString();
}
set
{
base.ConnectionString = value;
}
}
private string GetCurrentTenantConnectionString()
{
// TODO Implement your own logic
return $"Server=sample;Database=sample_{Context.User.UserName};Trusted_Connection=True;";
}
}
然后你需要MultiTenantPersistence
在配置文件中注册:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="Samples" type="CodeFluent.Runtime.CodeFluentConfigurationSectionHandler, CodeFluent.Runtime" />
</configSections>
<Samples persistenceHookTypeName="Sample.MultiTenantPersistence, Sample" />
</configuration>