Configuring Connection String in C# with Entity Framework Core
In this tutorial, we will extend the work from our previous article, demonstrating how to configure the connection string within our DbContext in a C# application. Establishing a proper connection string is pivotal for interacting with the database using Entity Framework Core (EF Core). The configuration can be done in various ways, depending on the type of application you are working on. However, for the sake of this article, we will showcase how to hard-code the connection string within the DbContext class, which is a straightforward method especially useful during the initial development phases.
When working with a web application, typically, the connection string is stored in a configuration file, which is a more secure and flexible approach. Nonetheless, hard-coding the connection string can be practical for testing purposes. Within the DbContext class, there's a method named OnConfiguring that we can override to set up the connection string. This method takes an argument of type DbContextOptionsBuilder, which provides a variety of configuration options.
In our previous article, we had added the NuGet package Microsoft.EntityFrameworkCore.SqlServer to our project, enabling us to work with SQL Server. Thanks to this package, we have access to the UseSqlServer method which allows us to specify our connection string.
To view the local connection string, one common approach is to use SQL Server Management Studio (SSMS). Upon launching SSMS and attempting to connect, if you have a single SQL Server instance on your machine, its name will be displayed. Otherwise, you can try connecting using localhost, which should work on the first attempt.
Below is an example of how you can hard-code the connection string within the OnConfiguring method of your ApplicationDbContext class:
public class ApplicationDbContext : DbContext
{
public DbSet<Article> Articles { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Server=DESKTOP-VSIUNDJ;Database=CheckEntityFrameworkCore;Trusted_Connection=True;TrustServerCertificate=true");
}
}
In this code snippet, we override the OnConfiguring method and utilize the UseSqlServer method on the optionsBuilder object, passing our connection string as an argument. This setup allows our application to interact with the specified SQL Server database using EF Core.
Utilizing EF Core for database interaction in C# applications provides a powerful, efficient, and code-centric approach to data access, making the task of configuring and managing database connections seamless.
领英推荐
keep on coding and always stay curious.
Software Engineer
6 个月Am using azure configs to store my connection string on the cloud..so how do I inject it on the application context class