我正在使用 VS 2015 CTP-6 测试新的 Asp.Net 5。由于 Entity Framework 7 中缺少功能,我现在更愿意使用 EF6。
我试过删除 EF7,然后在 PM 中应用 EF6,如下所示:
Uninstall-Package EntityFramework
Install-Package EntityFramework -version 6.1.3
没有返回错误,并且 project.json 文件似乎已相应更新。虽然,没有可用的 DbContext。
这有可能吗?如果是,我应该如何从这里开始?我是否需要 web.config 才能兼容 EF6?
最佳答案
是的,这很好用。
创建上下文时需要手动设置连接字符串,因为它无法从 web.config 中获取它
所以你可以这样做
public class MyContext : DbContext {
public MyContext(string connectionString) : base(connectionString) {
}
}
var context = new MyContext("myConnectionString");
如果你想从 config.json 中获取连接字符串,那么试试这个
IConfiguration configuration = new Configuration().AddJsonFile("config.json");
var connectionString = configuration["Data:DefaultConnection:ConnectionString"]);
如果你想将上下文注入(inject)到 DI 容器中,那么我添加了一个这样的工厂
public static class MyContextFactory
{
public static MyContext GetContext() {
IConfiguration configuration = new Configuration().AddJsonFile("config.json");
return new MyContext(configuration["Data:DefaultConnection:ConnectionString"]);
}
}
然后在startup.cs中添加这个
services.AddTransient<MyContext>((a) => MyContextFactory.GetContext());
关于c# - 如何在 Asp.Net 5 (MVC 6) 中使用 Entity Framework 6.x,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29296073/