更新时间:2023-02-24 12:01:54
是的,这工作正常。
您需要手动设置在创建上下文时连接字符串,因为它不能从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());