每個用戶都有一個數據庫。這意味着您需要在查詢數據庫之前更改連接字符串。隨着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>