in

NetCore 6.0 How to access connection string in dbContext file


Disclaimer:I am trying to learn more about net 6.0 and am a rookie.

Here is what i am trying to do:

  • I am trying to access IConfiguration file in a TransparencyContext but i keep on getting configuration being null error:System.ArgumentNullException: ‘Value cannot be null. (Parameter ‘connectionString’)’.

Here is what I did:

  • updated the dbContext’s constructor to inject IConfiguration config

TransparencyContext.cs

  namespace EFTutorial.Models
{
    public partial class TransparencyContext : DbContext
{
    private readonly IConfiguration config;

    public TransparencyContext()
    {
    }
    public TransparencyContext(IConfiguration config)
    {
        this.config = config;
    }

    public TransparencyContext(DbContextOptions<TransparencyContext> options)
        : base(options)
    {
    }

    public virtual DbSet<Fundraiser> Fundraisers { get; set; } = null!;
    public virtual DbSet<Person> Persons { get; set; } = null!;

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer(config.GetConnectionString("SQLDB"));
        }
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Fundraiser>(entity =>
        {
            entity.Property(e => e.Description).IsUnicode(false);

            entity.Property(e => e.EndDate).HasColumnType("datetime");

            entity.Property(e => e.Goal).HasColumnType("decimal(18, 2)");

            entity.Property(e => e.Name)
                .HasMaxLength(1000)
                .IsUnicode(false);
        });

        modelBuilder.Entity<Person>(entity =>
        {
            entity.Property(e => e.DateOfBirth).HasColumnType("datetime");

            entity.Property(e => e.FirstName)
                .HasMaxLength(100)
                .IsUnicode(false);

            entity.Property(e => e.LastName)
                .HasMaxLength(100)
                .IsUnicode(false);
        });

        OnModelCreatingPartial(modelBuilder);
    }

    partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}

}

Most of this Context file is automatically generated and the only thing i did was updated the public TransparencyContext(IConfiguration config) to include the Iconfig so i could access it in optionsBuilder.UseSqlServer(config.GetConnectionString("SQLDB"));

I try then to test it from home controller by doing this.

private TransparencyContext _transparencyContext;
        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
            _transparencyContext = new();
        }
public IActionResult Index()
        {
            var p = new Person();
            p.FirstName = "Entity";
            p.LastName = "Framework";

            _transparencyContext.Persons.Add(p);
            _transparencyContext.SaveChanges();
            return View();
        }

When i do this i get the config file( in TransparencyContext) being null (System.ArgumentNullException: ‘Value cannot be null(Parameter ‘connectionString’)’). I havent changed my program.cs and is the way it was when the project was created.

Program.cs

 var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

I know that configuration file can be accessed from app.Configuration but not sure how to make configuration accessible for the TransparencyContext.cs so i can get the connection string for db.I have tried looking at Microsoft documents but they don’t show how they make the Iconfiguration avaiable and only show them using it.Any help is much appreciated.

I am thinking I might need to register a service to configuration but not sure how to do it.



Source: https://stackoverflow.com/questions/70628152/netcore-6-0-how-to-access-connection-string-in-dbcontext-file

Next.js + Tailwind CSS + TypeScript starter packed with useful development features

Todo backend with python