我正在构建一个应该有 N 个 DataContexts 的项目。我有一个 Web 应用程序,它将在 App-Start (Global.asax) 中执行以下步骤:
1 - 如果数据库不存在,则创建。2 - 将数据库更新到最新的迁移。
当我第一次运行应用程序时(数据库尚未创建),我得到一个执行“无法打开登录请求的数据库“DBName”。登录失败。用户“sa”登录失败。”
好的,所以此时我检查数据库并创建它,但 __Migrations 表不存在。
如果我停止应用程序并再次运行它,则不会引发异常并且数据库已成功更新。
我尝试在我的连接字符串中设置持久安全信息,但没有任何变化。
我的代码如下: Global.asax
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
Bll.AppStart.Databases.Start();
}
打电话..
namespace BusinessLogicLayer.AppStart
{
/// <summary>
/// Inicialização e Update de versão dos bancos de dados do sistema
/// </summary>
public static class Databases
{
public static void Start()
{
//Iniciar DBCore
DataBaseStart<DataAccessLayer.DataContexts.Core.Context,
DataAccessLayer.Migrations.Core.Configuration>();
}
#region Inicializar bancos de dados
private static void DataBaseStart<T, TC>()
where T : DbContext, new()
where TC : DbMigrationsConfiguration<T>, new()
{
//Atualiza a base de dados com base na configuração do migrations
try
{
var migratorConfig = new TC();
var dbMigrator = new DbMigrator(migratorConfig);
dbMigrator.Configuration.AutomaticMigrationDataLossAllowed = false;
dbMigrator.Update();
}
catch (Exception)
{
//Exceção quando cria o banco a primeira vez?
throw new Exception("Banco de dados criado pela primeira vez. Reinicie a aplicação.");
}
}
#endregion
}
}
我的 Context 类..注意它定义了一个空数据库
public class Context : DbContext
{
public Context()
{
Database.Connection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["PODBCore"].ConnectionString;
}
public Context(string connectionString)
{
Database.Connection.ConnectionString = connectionString;
}
}
我的迁移配置类
public sealed class Configuration : DbMigrationsConfiguration<DataContexts.Core.Context>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
AutomaticMigrationDataLossAllowed = false;
}
protected override void Seed(DataContexts.Core.Context context)
{
// This method will be called after migrating to the latest version.
}
}
我有一个定义空模型的初始迁移
public partial class Initial : DbMigration
{
public override void Up()
{
}
public override void Down()
{
}
}
请记住,如果我运行该应用程序两次,则成功创建和更新数据库(我确实使用其他迁移进行了测试,创建表和东西)。仅在应用程序第一次运行时抛出异常,并且数据库不存在。
我还尝试在运行迁移更新代码之前调用 Database.SetInitializer 和 context.CreateIfNotExist()。
编辑:
我检查了 SQL Server 日志,基本上应用程序正在尝试连接到连接字符串中指定的初始目录,但它不存在。抛出异常后,数据库已创建并在线。
编辑:
如果我删除 Initial Catalog 属性,它将起作用,但是我将让我的所有 dataContexts 在主数据库中创建表。
我们可以有 N 个服务器实例,并且在上下文之间仍然存在某种分离,但我仍然试图在同一个 SQL 实例中按上下文获取一个目录