public async Task <ResultEx> InitDataBase(InstallSqlServerModel sqlServerModel) { var result = CheckSqlServerParameter(sqlServerModel); if (result.Flag) { _dataBaseName = result.Data.ToString(); string connectionString; if (!string.IsNullOrEmpty(sqlServerModel.ConnectionString)) { sqlServerModel.ConnectionString = sqlServerModel.ConnectionString.Trim(); } if (sqlServerModel.ConnectionType == ConnectionType.String) { connectionString = sqlServerModel.ConnectionString; } else { connectionString = CreateConnectionString( sqlServerModel.AuthenticationType == AuthenticationType.Windows, sqlServerModel.ServerName, sqlServerModel.DatabaseName, sqlServerModel.Username, sqlServerModel.Password); } //创建新的DBContext对象只是数据库创建操作 var builder = new DbContextOptionsBuilder(); builder.UseSqlServer(connectionString); var dbContext = new Kj1012Context(builder.Options); var dataBase = dbContext.Database; var databaseCreator = dataBase.GetService <IRelationalDatabaseCreator>(); sqlServerModel.ConnectionString = connectionString; var isCreateDatabase = false; if (sqlServerModel.AlwaysCreate) { if (databaseCreator.Exists()) { await databaseCreator.DeleteAsync(); } await CreateDataBase(databaseCreator, dataBase); isCreateDatabase = true; } else if (sqlServerModel.NotExistCreate) { if (!databaseCreator.Exists()) { await CreateDataBase(databaseCreator, dataBase); isCreateDatabase = true; } } else { if (!databaseCreator.Exists()) { return(ResultEx.Init(false, "数据库名称不存在,请核对")); } } var version = GetSqlServerVersion(sqlServerModel.ConnectionString); if (version < 10) { return(ResultEx.Init(false, "创建数据表失败,Sql Server 数据库版本至少需要Sql Server 2008及以上")); } if (version > 0) { //SQL Server2016 及以上执行2016脚本 if (version >= 13 && isCreateDatabase) { //执行2016脚本 ExecuteSqlScriptFromFile(dataBase, $"{SqlServerScriptPath}\\SqlServer_2016.sql"); } //保存数据库配置信息 _appSettingService.SaveDataSetting(new DataSettings { DataProvider = DataProviderType.SqlServer, Version = version, ConnectionString = AesHelper.AesEncrypt(sqlServerModel.ConnectionString, ConstDefine.DataSettingAesKey) }); } else { return(ResultEx.Init(false, "创建数据表失败,未知SQL SERVER数据库版本")); } } return(result); }