2016-03-15 160 views
-1

我有一个ASP .NET MVC 6和实体框架6,分为几层,我如何在DbContext中的DAL层获取连接字符串? 连接字符串是这样appsettings.json文件:ASP .NET MVC层DAL

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

我猜你添加一个构造函数说参数并推动它? – Carsten

回答

2

如果在连接字符串中appsettings.json要首先建立一个配置对象:

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

这也许应该是Startup 's ctor。然后,您可以将configuration对象存储在一个字段中。我们假设一个_configuration字段。

然后,你可以做

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

DbContext

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

的,你可以在ConfigureServicesAppDbContext注册为:

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

谢谢,现在我该如何在存储库类中运行查询? – henriquedpereira

+1

从这里开始应该很容易,如果你使用'DI',那么只需要在你仓库的ctor中请求'AppDbContext'。之后,像往常一样使用'AppDbContext'完成你的查询。如果您刚刚开始使用“EntityFramework”或“Asp.Net Core”,请告诉我们,以便我们知道如何最好地为您提供帮助。 – mrahhal