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("");