We spend thousands of hours creating application using EF6, and the structure we followed used EF6 framework into a separate class library layer, we are trying to switch to MVC 6 but still want to use EF6 class library project.
The problem we are currently facing is the connection string, we tried adding the connection string in applicationsettings.json
and then updated the Startup.cs
file accordingly, as suggested in the similar post How to Use Entity Framework 6.x in Asp.Net 5 (MVC 6)
public class MyContext : DbContext {
public MyContext(string connectionString) : base(connectionString) {
}
}
var context = new MyContext("myConnectionString");
but nothing seems to be working, not sure how to use the below lines in my .net 4.6 class library project or how can I access the applicationsettings.json
file?
IConfiguration configuration = new
Configuration().AddJsonFile("config.json");
var connectionString = configuration["Data:DefaultConnection:ConnectionString"]);
Option 1
public class MyContext : DbContext
{
public MyContext()
: base(new Configuration().AddJsonFile("config.json")["Data:DefaultConnection:ConnectionString"]);
{
}
{
Option 2
public class MyContext : DbContext
{
static readonly string ConnectionString;
static MyContext()
{
IConfiguration configuration = new Configuration().AddJsonFile("config.json");
ConnectionString = configuration["Data:DefaultConnection:ConnectionString"]);
}
public MyContext()
: base(ConnectionString);
{
}
}
Option 3
public class MyContext : DbContext
{
public MyContext(string connectionString)
: base(connectionString);
{
}
}
public static class ContextFactory
{
static readonly IConfiguration Configuration;
static ContextFactory()
{
Configuration = new Configuration().AddJsonFile("config.json");
}
public static MyContext CreateMyContext()
{
return new MyContext(Configuration["Data:DefaultConnection:ConnectionString"]);
}
}