首页 > 解决方案 > DotNet Core - 类库中的连接字符串

问题描述

我的 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

解决方案


***** 这是我对工作所做的更改 *****

我发现了我认为的问题,所以我们开始吧。

  1. 从 MySsdCaseContext 中删除以下内容。

    public MySsdCaseContext()
    {
    }
    

    并保留这个..

     public MySsdCaseContext(DbContextOptions<MySsdCaseContext> options) : base(options)
    {
    }
    
  2. 出于修复此注释的目的,请从 OnConfiguring 中删除以下内容。

    if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer("name=MySsdCaseDb");
        }
    
  3. 在 startup.cs 中,在 ConfigureService 方法中添加以下内容。

    services.AddDbContext<MySsdCaseContext>(options 
    =>options.UseSqlServer(Configuration.GetConnectionString("MySsdCaseDb")));
    

这应该会提示您添加对 MySsdCase.Core.Data 类库的引用。你目前没有这个。基本上将以下内容放在 startup.cs 的顶部

    using MySsdCase.Core.Data;
  1. 确保以下内容位于 MySsdCase.Web.cspoj 中

    <ItemGroup>
       <ProjectReference Include="..\MySsdCase.Core\MySsdCase.Core.csproj" />
    </ItemGroup>
    
  2. 像这样做...

          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。


推荐阅读