Reputation: 5058
I get an error of Object reference not set to an instance of an object
when I try to retrieve my data from a database. I know that EF has a dbcontext that I can use, but I want to try this approach as my colleagues use this kind. I can get the ConnectionString fine, I see it in my breakpoint, but after that line, I get the error:
System.Configuration.ConnectionStringSettingsCollection.this[string].get returned null
My code is below:
appsettings.json
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Server=DESKTOP-MIHT9TM\\SQLEXPRESS;Database=react_db;User=sa;Password=OtlPHP07"
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services
.AddMvc(options =>
{
options.EnableEndpointRouting = false;
})
.AddNewtonsoftJson()
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.IgnoreNullValues = true;
options.JsonSerializerOptions.WriteIndented = true;
});
services.AddSingleton<IConfiguration>(Configuration);
}
DepartmentController.cs
[Route("api/[controller]")]
[ApiController]
public class DepartmentController : ControllerBase
{
private readonly IConfiguration configuration;
public DepartmentController(IConfiguration configuration)
{
this.configuration = configuration;
}
[HttpGet]
public IActionResult Get()
{
DataTable table = new DataTable();
string query = @"SELECT * FROM dbo.Departments";
var conString = configuration.GetConnectionString("DefaultConnection");
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings[conString].ConnectionString))
{
using (var cmd = new SqlCommand(query, con))
{
using (var da = new SqlDataAdapter(cmd))
{
cmd.CommandType = CommandType.Text;
da.Fill(table);
}
}
}
return Ok(table);
}
}
I encounter the error on this line: using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings[conString].ConnectionString))
This is the value of the conString
I even tried this code...
var conString = configuration.GetConnectionString("DefaultConnection");
using (var con = new SqlConnection(ConfigurationManager.AppSettings[conString].ToString()))
Upvotes: 0
Views: 995
Reputation: 398
On the SqlConnection try using the configuration object that is passed on the constructor instead of a new instance of it. Or even better the conString variable you already have (which does use the configuration instance passed on the constructor)
Upvotes: 1