I have a controller class inside my ASP.NET server and I'm trying to get a list of all the data inside a table in my MySQL database. But for some reason my context variable inside my controller is null.
The error (on my context variable):
Object reference not set to an instance of an object
My controller class:
using Dyslexia.Managers;
using Dyslexia.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
namespace Dyslexia.Controllers
{
public class SchoolController : Controller
{
[HttpGet]
[Route("Api/Schools")]
public IEnumerable<SchoolModel> GetAllSchools()
{
SchoolManager context = HttpContext.RequestServices.GetService(typeof(SchoolManager)) as SchoolManager;
return context.GetAllSchools().ToArray();
}
}
}
My SchoolManager class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Dyslexia.Models;
using Microsoft.AspNetCore.Mvc;
using MvcSakilaCore.Models;
using MySql.Data.MySqlClient;
namespace Dyslexia.Managers
{
public class SchoolManager
{
public string ConnectionString { get; set; }
public SchoolManager(string connectionString)
{
ConnectionString = connectionString;
}
private MySqlConnection GetConnection()
{
return new MySqlConnection(ConnectionString);
}
public List<SchoolModel> GetAllSchools()
{
List<SchoolModel> schoolsList = new List<SchoolModel>();
using (MySqlConnection dbConnection = GetConnection())
{
dbConnection.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * FROM schools", dbConnection);
using (MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
schoolsList.Add(new SchoolModel()
{
Id = reader.GetInt32("Id"),
Name = reader.GetString("Name"),
Address = reader.GetString("Address"),
City = reader.GetString("City"),
PhoneNumber = reader.GetString("PhoneNumber"),
State = reader.GetString("State"),
Country = reader.GetString("Country"),
Zip = reader.GetString("Zip"),
AdminId = reader.GetInt32("AdminId"),
Active = reader.GetInt32("Active"),
});
}
}
}
return schoolsList;
}
}
}