将实体框架6类库项目与MVC 6

时间:2016-05-02 04:55:32

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

我们花费数千小时使用EF6创建应用程序,并且我们遵循的结构将EF6框架用于单独的类库层,我们正在尝试切换到MVC 6但仍希望使用EF6类库项目。

我们目前面临的问题是连接字符串,我们尝试在applicationsettings.json中添加连接字符串,然后相应地更新Startup.cs文件,如类似帖子How to Use Entity Framework 6.x in Asp.Net 5 (MVC 6)中所述< / p>

public class MyContext : DbContext {
  public MyContext(string connectionString) : base(connectionString) {
  }
}

var context = new MyContext("myConnectionString");

但似乎没有任何工作,不知道如何在我的.net 4.6类库项目中使用以下行,或者如何访问applicationsettings.json文件?

IConfiguration configuration = new 

Configuration().AddJsonFile("config.json");
var connectionString = configuration["Data:DefaultConnection:ConnectionString"]);

1 个答案:

答案 0 :(得分:2)

选项1

public class MyContext : DbContext
{
    public MyContext()
        : base(new Configuration().AddJsonFile("config.json")["Data:DefaultConnection:ConnectionString"]);
    {
    }
{

选项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);
    {
    }
}

选项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"]);
    }
}