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

前端 未结 5 740
情书的邮戳
情书的邮戳 2020-12-08 10:20

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 removi

5条回答
  •  时光取名叫无心
    2020-12-08 10:55

    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((a) => MyContextFactory.GetContext());
    

提交回复
热议问题