Using Entity Framework 6 class library project with MVC 6

asp.net-core-mvc c# connection-string entity-framework entity-framework-6

Question

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"]);
1
1
5/23/2017 10:29:44 AM

Accepted Answer

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"]);
    }
}
2
5/2/2016 5:25:42 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow