ConnectionString未初始化.net核心

时间:2019-08-01 19:03:32

标签: c# asp.net-core-mvc connection-string dapper

我转载了一种使用.net Framework访问数据库的方法,但该方法在.net Core中不起作用。我找到了一种修复它的方法,并按照所说的进行了操作,但是我收到了未初始化connectionString的错误。因此,我不知道如何使它工作。

我正在使用的代码:

public class DataAccess
{
    private string _connectionString;

    public DataAccess(string connectionString)
    {
        _connectionString = connectionString;
    }

    public List<PropertyModel> LoadData()
    {
        var data = new List<PropertyModel>();

        using(IDbConnection cnn = new SqlConnection(_connectionString))
        {
            data = cnn.Query<PropertyModel>(@"select *
                        from dbo.PropertyModel;").ToList();
        }
        return data;
    }
}

在控制器中:

private DataAccess data;

    public PropertyController(IOptions<ConnectionConfig> connectionConfig)
    {
        var connection = connectionConfig.Value;
        string connectionString = connection.Analysis;
        data = new DataAccess(connectionString);
    }

    public IActionResult Index()
    {
        var test = data.LoadData();
        return View();
    }

在启动中:

 services.Configure<ConnectionConfig
(Configuration.GetSection("MVCCoreAppDB"));

然后我创建了一个POCO类:

public class ConnectionConfig
{
    public string Analysis { get; set; }
}

我关注了this

appsettings.json:

"ConnectionStrings": {
"MVCCoreAppDB": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=MVCCoreAppDB;Integrated Security=True;Connect Timeout=60;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"},

1 个答案:

答案 0 :(得分:1)

您从配置中调用了错误的部分。

services.Configure<ConnectionConfig>(Configuration.GetSection("ConnectionStrings"));

您还需要更新模型

public class ConnectionConfig {
    public string MVCCoreAppDB { get; set; }
}

这就是说,我建议您更改设计以预先填充模型,并将其注册到用于注入的服务集合中

在启动中:

services.AddScoped<DataAccess>(_ => 
    new DataAccess(Configuration.GetConnectionString("MVCCoreAppDB"))
);

并将数据访问权限明确注入到控制器中

private readonly DataAccess data;

public PropertyController(DataAccess data) {
    this.data = data;
}

public IActionResult Index() {
    var test = data.LoadData();
    return View();
}

引用Explicit Dependencies Principle