System.InvalidOperationException: The ConnectionString property has not been initialized. - After upgrading from Ef Core 2.1.4 to 6.0.4.

Likhita Yadama 5 Reputation points
2023-05-05T12:18:32.9066667+00:00

Recently, I upgraded my project from .net core3 to .net6, as part of this upgrade I had to upgrade Entity framework core package from 2.1.4 to 6.0.4, I also changed the namespace System.data.SqlClient to Microosft.Data.SqlClient. After these changes, I am seeing runtime exceptions in my project.

Exception detail:

System.InvalidOperationException at Aclara.CE.Notification.Delivery.Data.NotificationDeliveryRepository+<GetNotificationDeliveryByRequestIdClientId>d__24.MoveNext

OuterMessage:

The ConnectionString property has not been initialized.

outerMethod:

Microsoft.Data.SqlClient.SqlConnection.PermissionDemand

Code:

 public async Task<Common.Entities.Delivery> GetNotificationDeliveryByRequestIdClientId(string notificationRequestId,
            int clientId)
        {
            Common.Entities.Delivery deliveryContext = null;
            try
            {
                deliveryContext = await (from delivery in _context.Delivery
                                         where delivery.NotificationRequestId == notificationRequestId
                                         where delivery.ClientId == clientId
                                         select delivery).FirstOrDefaultAsync();

            }
            catch (Exception ex)
            {
                Logger.LogCritical(ex, $"{DeliveryComponent}.{nameof(GetNotificationDeliveryByRequestIdClientId)}.Exception");
            }

            return deliveryContext;
        }

Context Class

 public NotificationDeliveryRepository(NotificationsDeliveryContext deliveryContext)
        {
            _context = deliveryContext;
        }

        public NotificationDeliveryRepository(string deliverySqlConnStr, ILogger logger)
        {
            var options = new DbContextOptionsBuilder<NotificationsDeliveryContext>().UseSqlServer(deliverySqlConnStr)
                .Options;
          
            _context = new NotificationsDeliveryContext(options);

            Logger = logger ?? throw new ArgumentException(nameof(logger));
        }

Startup.cs

 class Startup : FunctionsStartup {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            var configBuilder = new ConfigurationBuilder()
                // .SetBasePath(@"C:\\Aclara\\CommonComponents\\AppLib\\Aclara.CE.Notification.Delivery")
                .SetBasePath(Environment.CurrentDirectory)
                .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                .AddEnvironmentVariables()
                .Build();

            var settings = GetSettings(configBuilder);

            var config = configBuilder;

            var deliverySqlConnStr = config.GetConnectionString("DeliverySqlConnectionString") ??
                                     throw new Exception("DeliverySqlConnectionString configuration is missing");


            var notificationDeliveryFactory = new NotificationDeliveryFactory();
            var profile = new NotificationDeliveryMappingConfigProfile();
            var configProvider = new MapperConfiguration(cfg => cfg.AddProfile(profile));

            builder.Services.AddDbContextPool<NotificationsDeliveryContext>(options => options.UseSqlServer(deliverySqlConnStr));
            builder.Services.AddScoped<INotificationDeliveryRepository>(s => new NotificationDeliveryRepository(s.GetRequiredService<NotificationsDeliveryContext>()));
            builder.Services.AddSingleton<IConfiguration>(configBuilder);
            builder.Services.AddSingleton(settings);
            builder.Services.AddSingleton(configProvider);
            builder.Services.AddSingleton(notificationDeliveryFactory);
            
        }
											
Developer technologies .NET Entity Framework Core
Developer technologies ASP.NET ASP.NET Core
Developer technologies .NET Other
{count} votes

1 answer

Sort by: Most helpful
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2023-05-15T09:42:48.6+00:00

    Although you have resolved this, here is a way to validate your connection string which can be expanded on.

    Here I'm using a stock connection string from appsettings.json.

    Requires Microsoft.Data.SqlClient

    In Program.cs

    builder.Services.AddOptions<Connectionstrings>()
        .BindConfiguration(nameof(Connectionstrings))
        .ValidateDataAnnotations()
        .Validate(connections =>
        {
            if (string.IsNullOrEmpty(connections.DefaultConnection))
            {
                return false;
            }
    
            SqlConnectionStringBuilder connectionStringBuilder = new(connections.DefaultConnection);
            if (string.IsNullOrWhiteSpace(connectionStringBuilder.InitialCatalog))
            {
                return false;
            }
            
            return true;
    
        }, "Invalid connection string")
        .ValidateOnStart();
    

    Model

    public class Connectionstrings
    {
        public string DefaultConnection { get; set; }
    }
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.