This is my code but when I run it, I get a connection string that is always null. I also have the EntityFrameworkCore and SqlServer NuGet packages installed to.
The error I get is this:
System.NullReferenceException: 'Object reference not set to an instance of an object.' _connectionStrings was null.
appSettings.Development.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"ConnectionStrings": {
"MyDataContext": "[actual connection string]"
}
}
Startup.cs
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.Configure<ConnectionStrings>(Configuration.GetSection("ConnectionStrings"));
services.AddDbContext<MyDataContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MyDataContext")));
}
}
ConnectionStrings.cs
public class ConnectionStrings
{
public string MyDataContext { get; set; }
}
MyDataContext
public class MyDataContext : DbContext
{
public MyDataContext(DbContextOptions<MyDataContext> options) : base(options)
{
}
}
Index.cs.html
public class IndexModel : PageModel
{
private readonly ConnectionStrings _connectionStrings;
public IndexModel(ConnectionStrings connectionStrings)
{
_connectionStrings = connectionStrings;
}
public void OnGet()
{
StringBuilder sb = new StringBuilder();
string sql = "SELECT * FROM MyTable";
string connectionString = _connectionStrings.MyDataContext;
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlCommand command = new SqlCommand(sql, conn);
SqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
sb.Append(dr[0]);
}
conn.Close();
...
// Do more stuff with the sql data here
}
}
I also get a null reference to the object connection string. What am I missing?
Edit
I have added the constructor and now get this error:
InvalidOperationException: Unable to resolve service for type 'MyProject.ConnectionStrings' while attempting to activate 'MyProject.Pages.IndexModel'.
All the classes have namespace of MyProject with the exception of MyProject.Pages for the IndexModel page.
Solved
private readonly ConnectionStrings _connectionStrings;
public IndexModel(IOptions<ConnectionStrings> connectionStrings)
{
_connectionStrings = connectionStrings.Value;
}
Understaing DI and the Options pattern are important and need further reading.