1

I'd like to use DbConfiguration.SetDefaultConnectionFactory feature, which is to set the connection string "used to create connections by convention if no other connection string or connection is given to or can be discovered by DbContext".

But it seems like this can be used with Code-first only. If used in my project it goes to DbContext.OnModelCreating and throws UnintentionalCodeFirstException.

Are there any similar solution that can be used with DB-first or Model-first?

My code:

public class DbContext : System.Data.Entity.DbContext
{
    public DbContext() : base("ConnStrName") {}
    public DbContext(string connStr) : base(connStr) {}
    
    protected override void OnModelCreating(DbModelBuidler modelBuilder)
    {
        throw new UnintenionalCodeFirstException();
    }
}

public class EF6CodeConfig : DbConfiguration
{
    public EF6CodeConfig(IConfiguration configuration)
    {
        this.SetDefaultConnectionFactory(new ConnectionFactory(configuration));
    }
}

public class ConnectionFactory : IDbConnectionFactory
{
    public DbConnection CreateConnection(string nameOfConnStr)
    {
        var str = GetConnStr(nameOfConnStr);
        return new System.Data.Entity.Core.EntityClient.EntityConnection(str);
    }
}

And config EF:

DbConfiguration.SetConfiguration(new EF6CodeConfig(configuration));

Background about my situation: I'm creating a new .NET Core microservice referencing some old DLLs that used EF6. But EF6 cannot find the connection string from .NET Core appsettings file. So I need that fallback that SetDefaultConnectionFactory provides.

I have a work-around, but doesn't look good:

public class DbContext : System.Data.Entity.DbContext
{
    public static string ConnectionString { get; set; }
    private static string GetConnectionString(string connStrName)
    {
        return string.IsNullOrWhiteSpace(ConnectionString) ? connStrName : ConnectionString;
    }

    public DbContext : base(GetConnectionString("name=ConnStrName")) {}
    ...
}

And set the connection string myself:

DbContext.ConnectionString = configuration.GetConnectionString("");
Hp93
  • 1,349
  • 3
  • 14
  • 23
  • Does this answer your question? [Is there a way to change connection string in database first?](https://stackoverflow.com/questions/10508798/is-there-a-way-to-change-connection-string-in-database-first) – XAMT Oct 02 '20 at 07:20
  • No, I'm using .NET Core, it uses `appsettings.json` instead of `web.config`. Even if I add one EF6 still can't find the connection string. Using a different constructor can apply for new code but code from previous DLL that are using the default constructor won't work. – Hp93 Oct 02 '20 at 07:39

0 Answers0