网络核心连接字符串Dapper Visual Studio 2017 [英] Net Core Connection String Dapper visual studio 2017
问题描述
我试图在.Net Core应用程序中设置连接字符串,但我不断收到错误消息:
I am trying to get a Connection String set up in my .Net Core application but i keep getting the error:
System.NullReferenceException:'Object引用未设置为对象的实例。'
我尝试将以下内容添加到 appsettings.json 中:
I have tried adding the following to appsettings.json:
"ConnectionStrings": {
"Analysis": "Server=DESKTOP-MYSERVER;Database=MYDATABASE;User Id=sa; Password=Password123;Provider=System.Data.SqlClient;Trusted_Connection=True;MultipleActiveResultSets=true;Pooling=false;"
}
我也尝试过使用.net Core之前的web.config:
I also tried using web.config like I used to before .Net Core:
<connectionStrings>
<add name="Analysis" providerName="System.Data.SqlClient"
connectionString="Server=DESKTOP-MYSERVER;Database=MYDATABASE;User Id=sm;Password=Password123;"/>
然后在C#中我有:
public List<DapperTest> ReadAll()
{
var data = new List<DapperTest>();
using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["Analysis"].ConnectionString))
{
data = db.Query<DapperTest>("select * from testTable").ToList();
}
return data;
}
两种方式都给我以下例外:
Both ways give me the exception of:
System.NullReferenceException:'对象引用未设置为对象的实例。'
我使用了以下资源:
https://docs.microsoft.com/zh-cn/aspnet/core/data/ef-mvc/intro
但是我错过了一些东西。我只设置了一次连接字符串,但它不在.Net Core中,因此对其他人来说很明显。
But I am missing something. I have only set up connection strings once and it was not in .Net Core so it could be obvious to others.
推荐答案
如果使用的是appsettings.json,请创建一个简单的POCO类来对连接字符串配置进行建模,如下所示:
If you are using appsettings.json, create a simple POCO class to model your connection string configurations like this:
public class ConnectionConfig
{
public string Analysis {get;set;}
}
在Startup.cs的ConfigureServices方法中添加此行
Add this line in ConfigureServices method in Startup.cs
services.Configure<ConnectionConfig>(Configuration.GetSection("ConnectionStrings"));
数据服务等级
class YourClass{
private string _connectionString;
YourClass(string connectionString){
_connectionString = connectionString;
}
//Your implementation
public List<DapperTest> ReadAll()
{
var data = new List<DapperTest>();
using (IDbConnection db = new SqlConnection(_connectionString)
{
data = db.Query<DapperTest>("select * from testTable").ToList();
}
return data;
}
}
注入 IOptions< ConnectionConfig>
在您的控制器构造函数中。
Inject IOptions<ConnectionConfig>
in your controller constructor .
class YourController : Controller{
YourClass _testing;
YourController(IOptions<ConnectionConfig> connectionConfig){
var connection = connectionConfig.Value;
string connectionString = connection.Analysis;
_testing = new YourClass(connectionString );
}
public IActionResult Index() {
var testingData = _testing.ReadAll();
return View();
}
}
这篇关于网络核心连接字符串Dapper Visual Studio 2017的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!