gpt4 book ai didi

c# - Entity Framework 代码优先 : Migrate a database known only at runtime

转载 作者:太空狗 更新时间:2023-10-29 23:01:31 27 4
gpt4 key购买 nike

我正在尝试迁移仅在运行时已知的数据库,这意味着我无法使用程序包管理器控制台更新数据库。而且它不仅仅是一个,而是许多数据库,但它是所有数据库的相同模式:)

我正在使用 Ninject 生成连接字符串并将其注入(inject) DbContext 对象。上下文构造函数看起来像这样:

public class MyEntities : DbContext
{
public MyEntities(string database) : base(database) { }
/* Properties code omitted. */
}

实例化上下文的方法如下:

public MyEntities GetDatabase(string databaseName, string connectionString)
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString);
builder.InitialCatalog = databaseName;

MyEntities context = this._kernel.Get<MyEntities>(new ConstructorArgument(
"database", builder.ConnectionString));

Database.SetInitializer<MyEntities>(
new MigrateDatabaseToLatestVersion<MyEntities, MyEntitiesMigrationConfiguration>("MyEntities"));

return context;
}

当检索到上下文时,该方法会创建一个连接字符串并将其作为参数传递给 MyEntities 的构造函数。我还在方法中指定了我想要的迁移类型(在本例中为 MigrateDatabaseToLatestVersion)。

迁移代码如下:

public partial class MyAccountInMonth : DbMigration
{
public override void Up()
{
AlterColumn("AccountsInMonths", "MovementDebtMonth", c => c.Long(nullable: false));
AlterColumn("AccountsInMonths", "MovementCreditMonth", c => c.Long(nullable: false));
AlterColumn("AccountsInMonths", "BalanceMonth", c => c.Long(nullable: false));
AlterColumn("AccountsInMonths", "MovementDebtAccumulated", c => c.Long(nullable: false));
AlterColumn("AccountsInMonths", "MovementCreditAccumulated", c => c.Long(nullable: false));
AlterColumn("AccountsInMonths", "BalanceAccumulated", c => c.Long(nullable: false));
}

public override void Down() { /* Code omitted */ }
}

当我运行应用程序时,出现以下错误:

Cannot find the object "AccountsInMonths" because it does not exist or you do not have permissions.

迁移所做的是将 AccountsInMonths 列的类型从 int 更改为 long

这是一个迁移错误,因为堆栈跟踪调用了它。此时我只能认为问题可能是权限,因为表存在。其他可能性是连接字符串上的某种问题。拜托,有人对此有线索吗?提前致谢!

PS:如果不清楚我可以在问题中添加更多信息。

最佳答案

我有几个问题。这是解决方案:

1) 将您的 Configuration 作为公共(public)类:

public sealed class Configuration : DbMigrationsConfiguration<YourContextClassHere>

2) 将您的 Seed() 方法公开

2) 在任何地方添加下面的代码,这将应用最新的迁移并更新您的数据库:

Configuration configuration = new Configuration();
configuration.ContextType = typeof(YourContextClassHere);
var migrator = new DbMigrator(configuration);

// This will update the schema of the DB
migrator.Update();
// This will run Seed() method
configuration.Seed(new YourContextClassHere());

关于c# - Entity Framework 代码优先 : Migrate a database known only at runtime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10334885/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com