DEV Community

FOLASAYO SAMUEL OLAYEMI
FOLASAYO SAMUEL OLAYEMI

Posted on

How to connect ASP.NET Core code to MS SQL server

To connect your ASP.NET Core code to a Microsoft SQL Server database, you will need to follow these steps:

  • Install the necessary NuGet packages: Install the Microsoft.EntityFrameworkCore.SqlServer package, which includes the Entity Framework Core provider for Microsoft SQL Server.
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
Enter fullscreen mode Exit fullscreen mode
  • Create a connection string: Create a connection string that specifies the server name, database name, and any necessary authentication information. The connection string should be in the following format:
"Server=server_name;Database=database_name;User Id=user_id;Password=password;"

Enter fullscreen mode Exit fullscreen mode
  • Configure the DbContext: In your DbContext class, override the OnConfiguring method and use the UseSqlServer extension method to specify the connection string and any other options. For example:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UseSqlServer("Server=server_name;Database=database_name;User Id=user_id;Password=password;");
}

Enter fullscreen mode Exit fullscreen mode
  • Create your entity classes:
    Create POCO (plain old CLR object) classes to represent the entities in your database. These classes should be decorated with the [Table] attribute and the properties should be decorated with the [Column] attribute.

  • Create a DbSet for each entity:
    In your DbContext class, create a DbSet property for each entity in your model. For example:

public DbSet<Product> Products { get; set; }

Enter fullscreen mode Exit fullscreen mode
  • Run migrations: Use the Add-Migration and Update-Database commands in the Package Manager Console to apply your entity model to the database.
dotnet ef migrations add InitialCreate
dotnet ef database update

Enter fullscreen mode Exit fullscreen mode
  • Use LINQ to query the database: In your code, use LINQ queries to retrieve and manipulate data from the database. You can use the DbSet properties to access the entities in your model.

Thanks for reading...
Happy Coding!

Top comments (2)

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

Personally I do not recommend Entity Framework for web development. I have several reasons, some of them explained here. Nowadays I can enumerate a few performance reasons why EF is no good.

Instead I encourage any new developer to use Dapper.

Collapse
 
saint_vandora profile image
FOLASAYO SAMUEL OLAYEMI

Alright bro.
I will check it out.
But, I don't accept the idea of making people feel a tool is not good. EF as it pro and con, likewise Dapper. It's now left to the developer on which to choose.