DotNet Core-类库中的连接字符串

时间:2018-11-08 13:22:22

标签: .net-core

我与SQL的连接字符串存储在Web项目的appsettings.json中

  "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")));

1 个答案:

答案 0 :(得分:0)

*****这里是我所做的更改*****

我找到了我相信的问题,所以我们开始吧。

  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。

相关问题