我们花费数千小时使用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"]);
答案 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"]);
}
}