c# - 如何在 Asp.Net 5 (MVC 6) 中使用 Entity Framework 6.x

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

我正在使用 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/

相关文章:

c# - SSIS - 该进程无法访问该文件,因为它正被另一个进程使用

database - 在 Code First 中包含外键 ID 以保存查询?

c# - 找不到方法 : 'Void System.Data.Entity.DbModelBuilder.RegisterEntityType(System.Type)'

c# - Entity Framework 中的可更新 View 5/6

asp.net-core - 如何停止自托管 Kestrel 应用程序?

c# - 当结果为空时 LINQ 返回什么

c# - 无法审核插入 Entity Framework 。我陷入困境,你能帮忙吗?

c# - 使用互操作引发 vb6 事件

node.js - typescript 文件更改后 JavaScript 文件未更新

asp.net-core - 如何在 .Net Core 3.1 中的 OpenId 连接时禁用 ssl 证书验证?