1

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>(); 
4
  • builder.Services.AddScoped<DbContext, MyDbContext>(); - this should be removed it looks like a completely pointless registration Commented Apr 11, 2024 at 15:33
  • What is ConfigHelperDB? Why are you not using builder.Configuration.GetConnectionString? Commented Apr 11, 2024 at 15:34
  • after modifying it's working for me... removed : builder.Services.AddScoped<DbContext, MyDbContext>() modified ConfigHelperDB : builder.Configuration.GetConnectionString("DefaultConnection"), Thanks !!!!!!! Commented Apr 11, 2024 at 16:13
  • Was glad to help! Adding as an answer then. Commented Apr 11, 2024 at 16:18

1 Answer 1

0

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()));
Sign up to request clarification or add additional context in comments.

Comments

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.