如何使 EF 迁移工作,而无需在所需的无参数构造函数的基础中对名称或连接字符串进行硬编码?
EF 迁移迫使您将默认构造函数添加到自定义 dbcontext。在 dbcontext 的基础中,您必须提供名称或连接字符串。
public class CustomDbContext : DbContextBase
{
public CustomDbContext ()
: base("theconnectionstringwedontwanttoset") //hardcoded connection string
{
}
我们需要对构造函数进行硬编码这一事实是我们无法处理的,因为在我们的客户端应用程序中,我们在没有配置文件的情况下工作,并且我们动态地建立连接,因为我们正在连接到许多不同的数据库(服务器、本地 sql 紧凑型)。
在探索了 DbMigrationsConfiguration 类之后,我发现了一个名为 TargetDatabase 的 DbConnectionsInfo 属性,它可以在构造函数中设置。但即使这个解决方案也不起作用。这就是我所做的:
public sealed class Configuration : DbMigrationsConfiguration<CustomDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
//Setting the TargetDatabase in the hope it will use it in the migration
TargetDatabase = new DbConnectionInfo("Server=xxx;Database=xxx;Trusted_Connection=True", "System.Data.SqlClient");
}
public class MigrationInitializer : MigrateDatabaseToLatestVersion<CustomDbContext, Configuration>
{
}
我可以看到最终在 DbMigrator 中使用了 Activator.CreateInstance,我希望从这个类中使用 TargetDatabase.Create... 或其他东西。
欢迎任何帮助或反馈。
提前致谢,
威尔科
最佳答案
有可能是 See answers here
我还在这个问题中包含了一个测试程序。
关于entity-framework - 如何在没有硬编码 nameOrConnectionString 的情况下使用 EF CodeFirst 迁移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13474619/