Using Visual Studio and Dapper, how do I use a connection string?

.net-core asp.net asp.net-mvc c# dapper

Question

ZZZ_tmp
1
7
9/13/2017 3:30:50 AM

Accepted Answer

Create a simple POCO class to represent your connection string configurations if you're using the appsettings.json file, like this:

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

Add this line to the Startup.cs ConfigureServices function.

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

Class of data services

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;
   }
}

Inject IOptions<ConnectionConfig> in the constructor for your controller.

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(); 
     }
 }
6
9/13/2017 3:08:57 AM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow