entity-framework - 如何在没有硬编码 nameOrConnectionString 的情况下使用 EF CodeFirst 迁移

标签 entity-framework migration code-first dbcontext dbmigrator

如何使 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/

相关文章:

multithreading - Entity Framework 4.3和线程

ruby-on-rails - Rails:不能在迁移中通过change_column添加:precision或:scale选项吗?

c# - 在 FluentMigrator 上创建表之前检查表是否存在

asp.net-mvc-3 - Code First Entity Framework 连接字符串

c# - EntityFramework Fluent API 外键排序

entity-framework - 如何阻止 Entity Framework 生成 ObjectContext 和 dbContext

.net - 如何回滚实体删除而不丢失导航属性

entity-framework-4 - Entity Framework 4 - 与 CTP5 View 的一对多关系(代码优先)

c# - 使用 Entity Framework 6 创建计算字段

php - 如何修改 Laravel 中的迁移?