Home > Back-end >  How to point all connection string in generated strongly typed datasets to use appsettings default c
How to point all connection string in generated strongly typed datasets to use appsettings default c

Time:12-30

How can I point all generated dataset schema connection string to use appsettings default connection string in ASP.NET Core Razor pages?

Note: this works perfectly in ASP.NET Webforms and ASP.NET MVC, but not in ASP.NET Core with Razor pages.

Generated code from dataset Xsd Schema:

private void InitConnection()
{
    this._connection = new global::System.Data.SqlClient.SqlConnection();
    this._connection.ConnectionString = "Data Source=(localdb)\\mssqllocaldb;Initial Catalog=mylocaldb;Integrated Security=True";
}

I want the connection string to point to the appsettings.json default connection.

Thanks

CodePudding user response:

Below code in dotnet core should be same as yours.

services.AddScoped<IDbConnection, SqlConnection>(serviceProvider => {
    SqlConnection conn = new SqlConnection();
    conn.ConnectionString = 
             Configuration.GetConnectionString("Connectionstring");
    return conn;
});

For more details, you can refer below sample code:

How do I handle Database Connections with Dapper in .NET?

CodePudding user response:

Solution 1: (The simple way)

You could useIConfiguration interface. In the bellow code, I inject theIConfiguration interface to your code and use it.

Here is the code:

public class MyClass
{
   private  IConfiguration _configuration { get;}
    
   public MyClass(IConfiguration configuration)
   {
       _configuration = configuration;
   }

   private void InitConnection()
   {
       this._connection = new global::System.Data.SqlClient.SqlConnection();
       this._connection.ConnectionString = _configuration.GetConnectionString("DefaultConnection");
   }
}

and here is theappsettings.json file:

{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=(localdb)\\mssqllocaldb;Initial Catalog=mylocaldb;Integrated Security=True"
  },
  "AllowedHosts": "*"
}

Solution 2: (The best way)

Add a service in your startup.cs file and inject the service to your classes.

  • Related