我對使用實體框架使用Code First Migrations進行編碼。我正在使用一個自定義的構造函數,該構造函數具有特定於應用程序中登錄的某個用戶的連接字符串。使用自定義構造函數進行代碼優先遷移
當應用程序加載時,如果數據庫上下文有任何更改,我想用用戶連接字符串初始化數據庫並將其遷移到最新版本。我正在使用結構圖來注入工作單元。
全球ASAX
ObjectFactory.Configure(cfg =>
{
cfg.AddRegistry(new StandardRegistry());
cfg.AddRegistry(new ControllerRegistry());
cfg.AddRegistry(new ActionFilterRegistry(() => Container ?? ObjectFactory.Container));
cfg.AddRegistry(new MvcRegistry());
cfg.AddRegistry(new TaskRegistry());
cfg.AddRegistry(new ModelMetadataRegistry());
});
StandardRegistry類
For<ICustomerUnitOfWork>().Use(new CustomerUnitOfWork(new CustomerContext()));
For<CustomerContext>().Use(new CustomerContext());
在這一點上我不當知道用戶的ConnectionString因爲用戶沒有登錄。問題模型已經改變,結構圖會引發異常,因爲上下文模型已經改變。
語境
private static string _connectionString;
static CustomerContext()
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<CustomerContext, Configuration>());
}
public CustomerContext()
: base(string.IsNullOrEmpty(_connectionString) ? "FooDatabase" : _connectionString)
{
if (string.IsNullOrEmpty(_connectionString))
Database.SetInitializer(new CustomerContextInitializer());
}
public CustomerContext(string connectionString)
: base(connectionString)
{
if (string.IsNullOrEmpty(_connectionString))
Database.SetInitializer(new CustomerContextInitializer());
_connectionString = connectionString;
}
CustomerContextInitializer
public class CustomerContextInitializer : CreateDatabaseIfNotExists<CustomerContext>
{
protected override void Seed(CustomerContext context)
{
var informationService = new InformationService
{
ObjectState = ObjectState.Added,
ConnectorClass =
"Conexio.InformationService.Contracts.IInformationService, Conexio.InformationService.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
DisplayName = "IInformationService"
};
是有辦法的規則添加到standardRegistry類運行時調用與ConnectionString中constructur?還是有另一種方法來解決這個問題?