Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 views
in Technique[技术] by (71.8m points)

c# - How to Use Entity Framework 6.x in Asp.Net 5 (MVC 6)

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.

I've tried removing EF7 and then applying EF6 in PM, like this:

Uninstall-Package EntityFramework
Install-Package EntityFramework -version 6.1.3

No errors returned, and the project.json file seems updated accordingly. Although, there are no DbContext available.

Is this at all possible? If yes, how should I proceed from here? Do I need web.config for EF6 compatibility?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, this works fine.

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");

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"]);

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"]);
    }

}

and then added this in startup.cs

services.AddTransient<MyContext>((a) => MyContextFactory.GetContext());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...