【发布时间】:2018-11-13 21:23:25
【问题描述】:
我的 SQL 连接字符串存储在 appsettings.json 中的 Web 项目中
"ConnectionStrings": {
"MyDbConnectionString": "***"
},
然后我使用 Scaffold 添加了一个数据库上下文
Scaffold-DbContext -Connection "name=MyDbConnectionString" -Provider "Microsoft.EntityFrameworkCore.SqlServer" ... -Force
我可以在控制器中使用上下文,并且在获取数据或写入方面没有问题。但是,我希望我所有的业务逻辑都在一个单独的类库上。所以这是我的图书馆中的存储库:
public class MyRepository
{
private static MyContext CurrentContext
{
get { return new MyContext(); }
}
public static async void AddEventLog(EventLog eventLog)
{
using (var context = CurrentContext)
{
context.EventLog.Add(eventLog);
await context.SaveChangesAsync();
}
}
}
但它在尝试写入数据库时失败。
System.InvalidOperationException: 'A named connection string was used, but the name 'MyDbConnectionString' was not found in the application's configuration.
我是否应该将 appsettings.json 添加到库项目中(这似乎是多余的,不正确的)?我错过了什么?如何引用回 Web 项目 appsettings.json 文件?
任何帮助将不胜感激。
这是我的创业公司
services.AddDbContext<MyContext>(options =>options.UseSqlServer(Configuration.GetConnectionString("MyDbConnectionString")));
【问题讨论】:
标签: .net-core