7

How can I connect to a database from ASP.NET Core and Angular without Entity Framework?

 "ConnectionStrings": {
    "DefaultParkingConnection": "Server=DESKTOP-CD0M0C3\\SQLEXPRESS;Database=ParkingSystem2;Trusted_Connection=True;MultipleActiveResultSets=true;User ID=sa;Password=P@ssw0rd"
  }, 

How can I get connection string in Web API controller?

string constr = ConfigurationManager.ConnectionStrings["DefaultParkingConnection"].ConnectionString;
0

3 Answers 3

6

ASP.NET Core works different than ASP.NET, so you need to map the connection strings defined in appsettings.json to a class or variable to be accessed throughout the application. Try the following approach:

  1. Create appSettings.json:

    {
    "ConnectionStrings": {
        "DefaultParkingConnection": "Server=DESKTOP-CD0M0C3\\SQLEXPRESS;Database=ParkingSystem2;Trusted_Connection=True;MultipleActiveResultSets=true;User ID=sa;Password=P@ssw0rd"
      }
    }
    
  2. Create a new class ConnectionStrings to map the connection strings defined in appSettings.json to it:

    using System;
    
    namespace Test
    {
        public class ConnectionStrings 
        {
            public string DefaultParkingConnection{ get; set; }
        }
    }
    
  3. In Startup.cs, write the following code:

    public class Startup
    {
        public IConfiguration Configuration { get; }
    
        public Startup(IConfiguration configuration)
        {
            this.Configuration = configuration;
        }
    
        public void ConfigureServices(IServiceCollection services)
        {
            //Map the configuration
            var connectionSection = Configuration.GetSection("ConnectionStrings");
            services.Configure<ConnectionStrings>(connectionSection );            
        }
    
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            // Configure 
        }
    }
    
  4. Now in your controllers, you can easily use it without creating the instance of the class:

    using Microsoft.AspNetCore.Authentication.JwtBearer;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Options;
    
    namespace Test.Controllers
    {
        [ApiController]
        [Route("api/account")]
        public class AccountController : ControllerBase
        {
            private readonly ConnectionStrings connectionStrings;
    
            public AccountController(IOptions<ConnectionStrings> connectionStrings)
            {
                this.connectionStrings = connectionStrings.Value;
            }
    
            [HttpGet, Route("test")]
            public IActionResult Test()
            {
                return Ok("test");
            }
        }
    }
    
Sign up to request clarification or add additional context in comments.

2 Comments

How do I access the route to know if there was a connection?
This answer would benefit from being updated to reflect the .NET 6+ reality of Startup.cs being merged into Program.cs (in other words, in .NET 6+ there is no Startup.cs file anymore).
5

You could inject IConfiguration in api controller:

public class ValuesController : Controller
{
    public IConfiguration _configuration { get; }

    public ValuesController(IConfiguration configuration)
    {
        _configuration = configuration;

        string constr  = _configuration.GetConnectionString("DefaultParkingConnection");
    }
}

Comments

0

Microsoft has just release sqlclient for asp.net core for access to ado.net.

from the packagemanager

Install-Package Microsoft.Data.SqlClient -Version 1.0.19269.1

1 Comment

This has the beginnings of being useful, but it doesn't explain how to connect to a database, just that there is a library that may or may not add support for it. You can improve this answer by editing it and adding an explanation on how to use Microsoft.Data.SqlClient to create a connection to a database.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.