问题描述
我正在使用 VS 2015 CTP-6 测试新的 Asp.Net 5.由于 Entity Framework 7 中缺少功能,我现在更喜欢使用 EF6.
I'm testing out the new Asp.Net 5, using VS 2015 CTP-6. Because of the lack of features in Entity Framework 7, I would prefer using EF6 for now.
我已尝试删除 EF7,然后在 PM 中应用 EF6,如下所示:
I've tried removing EF7 and then applying EF6 in PM, like this:
Uninstall-Package EntityFramework
Install-Package EntityFramework -version 6.1.3
没有返回错误,并且 project.json 文件似乎相应更新.虽然,没有可用的 DbContext.
No errors returned, and the project.json file seems updated accordingly. Although, there are no DbContext available.
这有可能吗?如果是,我应该如何从这里开始?我是否需要 web.config 才能与 EF6 兼容?
Is this at all possible? If yes, how should I proceed from here? Do I need web.config for EF6 compatibility?
推荐答案
是的,这很好.
创建上下文时需要手动设置连接字符串,因为无法从web.config中获取
You need to manually set the connection string when creating the context since it can't get it from the web.config
所以你可以这样做
public class MyContext : DbContext {
public MyContext(string connectionString) : base(connectionString) {
}
}
var context = new MyContext("myConnectionString");
如果你想从 config.json 中获取连接字符串,那么试试这个
if you want to get the connection string from the config.json, then try this
IConfiguration configuration = new Configuration().AddJsonFile("config.json");
var connectionString = configuration["Data:DefaultConnection:ConnectionString"]);
如果你想将上下文注入到 DI 容器中,那么我添加了一个这样的工厂
and if you want to inject the context into the DI Container, then I added a factory like this
public static class MyContextFactory
{
public static MyContext GetContext() {
IConfiguration configuration = new Configuration().AddJsonFile("config.json");
return new MyContext(configuration["Data:DefaultConnection:ConnectionString"]);
}
}
然后在startup.cs中添加这个
and then added this in startup.cs
services.AddTransient<MyContext>((a) => MyContextFactory.GetContext());
这篇关于如何在 Asp.Net 5 (MVC 6) 中使用实体框架 6.x的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!