sql-serverlinqasp.net-coreasp.net-core-mvclinq-to-entities

System.InvalidOperationException: 'The ConnectionString property has not been initialized.' in ASP.NET Core 8, Entity Framework and Linq


I am using ASP.NET Core 8, Entity Framework and Linq to connect to a SQL Server database, but I am getting this error

System.InvalidOperationException: the ConnectionString property has not been initialized

while trying to fetch data from the SQL Server database. I am not using Startup.cs - instead I'm using program.cs.

Here is my code:

public class MasterDAL : IMasterDAL
{
    private readonly MyDbContext _context;
    IConfiguration _configuration;

    public MasterDAL(MyDbContext context, IConfiguration configuration)
    {
        _context = context;
        _configuration = configuration;
    }
 
    public IEnumerable<CategoryViewModel> getCategory()
    {
        List<CategoryViewModel> categoryModel = new List<CategoryViewModel>();

        categoryModel = (from cat in _context.CategoryMasters.AsNoTracking()
                         select new CategoryViewModel
                                {
                                    CategoryId = cat.CategoryMasterId,
                                    CategoryName = cat.CategoryName
                                }).Distinct().ToList();

        return categoryModel;
    }
}

DbContext:

public partial class MyDbContext : DbContext
{
    private readonly IConfiguration _config;

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

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer(ConfigHelperDB.GetConnectionString("DefaultConnection"),
            options => options.EnableRetryOnFailure());
        }
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<CategoryMaster>(entity =>
             {
                 entity.HasKey(e => e.CategoryMasterId)
                       .HasName("PK_CategoryMaster_CategoryMasterId");

                 entity.Property(e => e.CreatedDate)
                       .HasDefaultValueSql("(getdate())");
             });

        OnModelCreatingPartial(modelBuilder);
    }

    partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}

Program.cs:

builder.Services.AddDbContextPool<MyDbContext>(
    options => options.UseSqlServer(ConfigHelperDB.GetConnectionString("DefaultConnection"),
    options => options.EnableRetryOnFailure()));

builder.Services.AddScoped<DbContext, MyDbContext>();

Please help me solve this error.

I have tried removing

builder.Services.AddScoped<DbContext, ExpenseDbContext>(); 

also I tried adding

builder.Services.AddTransient<DbContext, ExpenseDbContext>(); 

Solution

  • Remove the following:

    builder.Services.AddScoped<DbContext, ExpenseDbContext>(); 
    

    And use Configuration from builder to get the connection string:

    builder.Services.AddDbContextPool<MyDbContext>(
        options => options.UseSqlServer(builder.Configuration.GetConnectionString("..."),
        options => options.EnableRetryOnFailure()));