I have a .NET Core 3.0 class library. It is my first time working with .NET Core
I want to connect to a database.
https://learn.microsoft.com/en-us/ef/core/miscellaneous/connection-strings shows exactly how to do it.
https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.configuration.configurationextensions.getconnectionstring?view=dotnet-plat-ext-3.1 shows the method which exists in the Microsoft.Extensions.Configuration
namespace
I can't access it.
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration; //no underlines and imported via Nuget
namespace Core.Cms.DAL
{
public class Entities : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{ optionsBuilder.UseSqlServer(Microsoft.Extensions.Configuration.GetConnectionString(ConnectionString.SqlServerExpress));
}
}
}
Screenshot
Why do I not have the Microsoft.Extensions.Configuration.GetConnectionString()
method available?
edit
Restarted rider - same issue
Entities.cs(17, 45): [CS0234] The type or namespace name 'GetConnectionString' does not exist in the namespace 'Microsoft.Extensions.Configuration' (are you missing an assembly reference?)
In .NET 6 you now use builder.Configuration.GetConnectionString like this
builder.Services.AddDbContext<ApplicationDBContext>(options =>
options.UseSqlServer(
builder.Configuration.GetConnectionString("DefaultConnection")
));
You should use the IConfiguration
interface. you can access to configuration form DI
like this
private readonly IConfiguration _configuration;
public Entities(IConfiguration configuration)
{
_configuration = configuration
}
then use the _configuration.GetConnectionString(ConnectionString.SqlServerExpress)
instead of Microsoft.Extensions.Configuration.GetConnectionString()
optionsBuilder.UseSqlServer(_configuration.GetConnectionString(ConnectionString.SqlServerExpress));
if you are using the Asp.Net Core Web Application, This is a better way to config DbContext in startup class
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; set; }
services.AddDbContext<Entities>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString(ConnectionString.SqlServerExpress));
});
Update
if you don't use the DI
you can access to IConfiguration
manually.
first you must install this packages
Microsoft.Extensions.Configuration.Json
Microsoft.Extensions.Configuration.FileExtensions
then build the IConfiguration
IConfiguration configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", true,true)
.Build();
optionsBuilder.UseSqlServer(configuration.GetConnectionString(ConnectionString.SqlServerExpress));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With