Access SQL Server Database In .NET Core Console Application

Introduction

To access a SQL Server database in a .NET Core console application, you’ll need to follow these general steps:

  1. Install NuGet Packages:
    Open your console application project in Visual Studio or a text editor, and add the necessary NuGet packages to enable SQL Server database connectivity:
   dotnet add package Microsoft.EntityFrameworkCore.SqlServer
   dotnet add package Microsoft.EntityFrameworkCore.Design

These packages provide Entity Framework Core and the SQL Server provider.

  1. Create Entity Classes:
    Define your entity classes that represent the tables in your database. These classes will map to the database schema.
   public class Product
   {
       public int Id { get; set; }
       public string Name { get; set; }
       // ... other properties
   }
  1. Create a DbContext:
    Create a class that inherits from DbContext, which represents the database context and provides access to your entities.
   public class MyDbContext : DbContext
   {
       public DbSet<Product> Products { get; set; }

       protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
       {
           optionsBuilder.UseSqlServer("Your_Connection_String");
       }
   }

Replace "Your_Connection_String" with the actual connection string to your SQL Server database.

  1. Query and Manipulate Data:
    In your console application’s Program.cs or another appropriate file, use your DbContext to query and manipulate data.
   class Program
   {
       static async Task Main(string[] args)
       {
           using (var dbContext = new MyDbContext())
           {
               var products = await dbContext.Products.ToListAsync();

               foreach (var product in products)
               {
                   Console.WriteLine($"Product ID: {product.Id}, Name: {product.Name}");
               }
           }
       }
   }
  1. Run the Console Application:
    Run your console application to access and manipulate data in the SQL Server database.

Remember to replace placeholders with actual database details and adjust the code according to your specific requirements. This is just a basic example to get you started. Entity Framework Core provides a powerful way to interact with databases, supporting features like migrations, LINQ queries, and more.

Leave a Reply

Your email address will not be published. Required fields are marked *