我的SQL连接字符串存储在appsettings.json 中的Web项目中
"ConnectionStrings": {
"MyDbConnectionString": "***"
},
然后我使用Scaffold 添加了一个DB上下文
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")));
*****以下是我对作品所做的更改*****
我发现了我认为的问题,所以我们开始吧。
-
从MySsdCaseContext中删除以下内容。
public MySsdCaseContext() { }
并保留这个。。
public MySsdCaseContext(DbContextOptions<MySsdCaseContext> options) : base(options) { }
-
为了修复此注释,请从OnConfiguring中删除以下内容。
if (!optionsBuilder.IsConfigured) { optionsBuilder.UseSqlServer("name=MySsdCaseDb"); }
-
在startup.cs中,在ConfigureService方法内部添加以下内容。
services.AddDbContext<MySsdCaseContext>(options =>options.UseSqlServer(Configuration.GetConnectionString("MySsdCaseDb")));
这将提示您添加对MySsdCase的引用。果心数据类库。您当前没有此。基本上startup.cs 顶部的以下内容
using MySsdCase.Core.Data;
确保以下内容在MySsdBase中。Webspoj
<ItemGroup> <ProjectReference Include="..MySsdCase.CoreMySsdCase.Core.csproj" /> </ItemGroup>
这样做。。。
public class EventLogRepository { private readonly MySsdCaseContext _context; public async Task AddEventLogAsync(EventLog eventLog) { var myVar = await _context.Set<ClientDetails>() .AsNoTracking() .Select(p => p) .Take(2) .ToListAsync(); } }
我认为总体而言,在startup.cs.中没有提及BL的DAL