Why ConfigurationManager.ConnectionStrings returns only a default LocalDb ASP.Net Cnx?

25 views Asked by At

I am in the process of upgrading a .NET 4.7.1 project to .NET 8. This project is using EF 6 and needs a connection strings from the configuration file. To my surprise, the connection I am requesting is missing from the ConnectStringSettingsCollection. Futhermore, this collection contains only one connexion, that is a default LocalDb one :

data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true

I have tried to run the following code in a brand new .Net 8.0 console project.

using System.Configuration;

string _endpoint = System.Configuration.ConfigurationManager.AppSettings["endpoint"]!;
string _connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["sqlServer"]!.ConnectionString;

Console.WriteLine($"Endpoint: {_endpoint}");
Console.WriteLine($"Connection String: {_connectionString}");  

The project file is :

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="System.Configuration.ConfigurationManager" Version="8.0.0" />
  </ItemGroup>

</Project>

The config file :

<?xml version="1.0"?>
<configuration>
    <appSettings>
        <add key="endpoint" value="https://endpoint.somewhere.com/" />
    </appSettings>
    <connectionStrings>  
        <add
            name="sqlServer"
            providerName="System.Data.SqlClient"
            connectionString="Data Source=localhost;Initial Catalog=MyDB;Integrated Security=True;" />
    </connectionStrings>
</configuration>

This code works perfectly, the connection string is correctly found.

As a side note, I am working with .NET Core on a MacBook, not on a Windows Machine. But I have tested the code that does not work on a windows machine and the problem remains the same.

Edit : This project is a library, and I'm using a MS Test project, also migrated to .NET 8, to test if EF 6 is correctly running on .NET 8.

1

There are 1 answers

0
Olivier MATROT On

After my edit regarding the usage of an MS Test project to consume my upgraded library, I searched again.

And I found my exact problem.

As the contributor suggested, I've added the MSBuild Task snippet in my test project's .csproj file right before the closing </project> node, and the problem is solved.