c# – Net Core Connection String Dapper visual studio 2017

前端之家收集整理的这篇文章主要介绍了c# – Net Core Connection String Dapper visual studio 2017前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图在我的.Net Core应用程序中设置连接字符串,但我一直收到错误

System.NullReferenceException:’对象引用未设置为对象的实例.’

我尝试将以下内容添加到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;"
}

我也试过像以前那样使用web.config .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;
    }

两种方式都给我例外:

System.NullReferenceException:’对象引用未设置为对象的实例.’

我使用了以下资源:

.Net CORE Dapper Connection String?

https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/intro

Get connection string from App.config

但我错过了一些东西.我只设置了一次连接字符串,它不在.Net Core中,因此对其他人来说显而易见.

解决方法

如果您正在使用appsettings.json,请创建一个简单的POCO类来为您的连接字符串配置建模,如下所示:
public class ConnectionConfig
{
        public string Analysis {get;set;}
}

在Startup.cs中的ConfigureServices方法添加此行

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>在你的控制器构造函数中.

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(); 
     }
 }
原文链接:https://www.f2er.com/netcore/100200.html

猜你在找的.NET Core相关文章