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());
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…