0

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))

Edit

This is the value of the conString

enter image description here

I even tried this code...

var conString = configuration.GetConnectionString("DefaultConnection");
            using (var con = new SqlConnection(ConfigurationManager.AppSettings[conString].ToString()))
6
  • it should be: using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString)) Commented May 17, 2020 at 6:09
  • The DefaultConnection is in my appsettings.json not in the WebConfig, Sir. Commented May 17, 2020 at 6:12
  • what is the value of "conString" variable/ Commented May 17, 2020 at 6:15
  • @LaxmiLalMenaria, Please see my edit Commented May 17, 2020 at 6:18
  • 2
    you already have connection string so you can directly use using (var con = new SqlConnection(conString)) Commented May 17, 2020 at 6:23

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

2 Comments

I didn't create a new instance, SIr. I just used the "coniguration" that was passed. Anyways, I tried doing what you suggested. I directly used the connection string. like so... conString2 = configuration.GetConnectionString("DefaultConnection");
Yes. Sorry I didn’t made myself clear. I mean, on the SqlConnection just use the conString variable instead of looking it up again.

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.