如何使用Asp.Net 5(MVC 6)实体框架6.x的 [英] How to Use Entity Framework 6.x in Asp.Net 5 (MVC 6)

查看:1254
本文介绍了如何使用Asp.Net 5(MVC 6)实体框架6.x的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我测试了新的Asp.Net 5,使用VS 2015年CTP-6。由于实体框架7缺乏特色,我想preFER使用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

这样你就可以做到这一点。

so you can do this

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的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆