【问题标题】:ASP .NET MVC layer DALASP .NET MVC 层 DAL
【发布时间】:2016-03-15 22:39:49
【问题描述】:

我有一个 ASP .NET MVC 6 和 Entity Framework 6,分为多个层,如何在我的 DbContext 中获取 DAL 层中的连接字符串? 连接字符串在 appsettings.json 文件中,如下所示:

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Verbose",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "Data": {
    "DefaultConnection": {
      "ConnectionString": "",
    }
  }
}

【问题讨论】:

  • 我猜你添加了一个带有上述参数的构造函数并通过它?

标签: asp.net-mvc entity-framework-6


【解决方案1】:

如果你在appsettings.json中有连接字符串,你想先构建一个配置对象:

var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");
var configuration = builder.Build();

这应该在Startup 的ctor 中。然后,您可以将 configuration 对象存储在字段中。假设是 _configuration 字段。

那你就可以了

// _connectionString is also a field.
_connectionString = _configuration["Data:DefaultConnection"];

你的DbContext

public class AppDbContext : DbContext
{
    public AppDbContext(string connectionString) : base(connectionString)
    {
    }
}

您可以在ConfigureServices 中注册您的AppDbContext 为:

services.AddScoped(_ => new AppDbContext(_connectionString));

【讨论】:

  • 谢谢,现在如何在我的存储库类中运行查询?
  • 从这里开始应该很容易,如果您使用的是DI,那么只需在存储库的ctor 中请求AppDbContext。之后,像往常一样使用AppDbContext 进行查询。如果您刚开始使用EntityFrameworkAsp.Net Core,请告诉我们,以便我们知道如何为您提供最好的帮助。
猜你喜欢
  • 2014-04-08
  • 2016-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-02
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
相关资源
最近更新 更多