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

FOLASAYO SAMUEL OLAYEMI - Dec 16 '22 - - Dev Community

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!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player