Close Menu

    Subscribe to Updates

    Get the latest creative news from FooBar about art, design and business.

    What's Hot

    5G Advanced 2026: Real Speeds and Coverage You Can Expect Review: Brutally Honest Assessment

    April 18, 2026

    Best Foldable Phones 2026: Samsung Google OnePlus Comparison: The Complete Breakdown Nobody Asked For

    April 17, 2026

    Tech Jobs 2026: Highest Paying Roles and Skills in Demand Review: Brutally Honest Assessment

    April 17, 2026
    Facebook X (Twitter) Instagram
    • About Us
    • Privacy Policy
    • Submit post
    Facebook LinkedIn
    Login
    DastgeerTech StudioDastgeerTech Studio
    • Home
    • Technology

      Top Car Technologies in 2025: Best Features and Leading Car Variants

      November 21, 2025
      Read More

      Apple Event 2025: Hurrah! Apple Set to dazzle the World with the Groundbreaking Next-Gen iPhone & Apple Watch on September 9

      September 5, 2025
      Read More

      Angular Deferred Loading with @defer: Complete Guide to Faster Load Times & Better UX

      September 3, 2025
      Read More

      GitHub for Developers: The Ultimate Guide to Mastering Version Control, Collaboration

      April 19, 2025
      Read More

      Samsung Galaxy A56 Review: Is It Still the Mid-Range King?

      April 15, 2025
      Read More
    • People’s Favorite
    • Featured
    • Angular

      What is a PWA? The Future of Mobile-First Web Experience

      October 21, 2025
      Read More

      Angular Deferred Loading with @defer: Complete Guide to Faster Load Times & Better UX

      September 3, 2025
      Read More

      Learn Angular A Comprehensive Guide with Examples

      April 11, 2025
      Read More

      Email Automation with Node.js & Angular: Step-by-Step 2025

      April 1, 2025
      Read More

      Advanced JavaScript Coding Questions and Answers

      February 26, 2025
      Read More
    • Gadgets
    • Blog
        Featured

        Best Gaming: A Look at the Best Gaming Experiences in 2024

        adminJune 30, 2024
        Read More
        Recent

        Best Value Flagship Phones 2026: Top Picks & Reviews

        February 28, 2026

        AI Won’t Replace Web Developers – But THIS Will Change Everything 2026

        November 29, 2025

        How to Fix a Slow Loading Website: 2025 Guide for Beginners

        November 29, 2025
      DastgeerTech StudioDastgeerTech Studio
      Home » .NET Core database connection Methods, Steps, and Best Practices
      .Net

      .NET Core database connection Methods, Steps, and Best Practices

      adminBy adminSeptember 15, 2024No Comments4 Mins Read
      Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
      .NET Core database connection Methods, Steps, and Best Practices
      Share
      Facebook Twitter LinkedIn Pinterest Email

      .NET Core database connection Learn how to connect SQL Server with .NET Core through ADO.NET, Entity Framework Core, and Dapper. This comprehensive guide covers step-by-step instructions and best practices for each method.

      Connecting SQL Server with .NET Core is a common task for developers looking to build robust, data-driven applications. .NET Core, now known as .NET 5 and later versions, provides several ways to connect to SQL Server. This article outlines the primary methods for connecting SQL Server with .NET Core and explains each method step by step.

      .NET Core database connection Methods, Steps, and Best Practices

      Table of Contents

      • 1. Using ADO.NET
      • 2. Using Entity Framework Core
      • 3. Using Dapper
      • Conclusion

      1. Using ADO.NET

      ADO.NET is a data access technology that provides a set of classes for connecting to databases, executing commands, and managing data. .NET Core database connection Here’s how to use ADO.NET with .NET Core:

      Nx Monorepo: The Future of Web Development

      .NET Core database connection Methods, Steps, and Best Practices Step-by-Step Guide:

      1. Install the SQL Server NuGet Package:
        Open your terminal or package manager console and install the System.Data.SqlClient package, which is necessary for SQL Server interactions.
         dotnet add package System.Data.SqlClient
      1. Configure Your Connection String:
        Add your connection string to the appsettings.json file.
         {
           "ConnectionStrings": {
             "DefaultConnection": "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;"
           }
         }
      1. Create a Data Access Class:
        Create a class that uses SqlConnection, SqlCommand, and SqlDataReader to interact with SQL Server.
         using System;
         using System.Data.SqlClient;
         using Microsoft.Extensions.Configuration;
      
         public class DataAccess
         {
             private readonly string _connectionString;
      
             public DataAccess(IConfiguration configuration)
             {
                 _connectionString = configuration.GetConnectionString("DefaultConnection");
             }
      
             public void GetData()
             {
                 using (SqlConnection connection = new SqlConnection(_connectionString))
                 {
                     connection.Open();
                     SqlCommand command = new SqlCommand("SELECT * FROM YourTable", connection);
                     SqlDataReader reader = command.ExecuteReader();
      
                     while (reader.Read())
                     {
                         Console.WriteLine(reader["ColumnName"].ToString());
                     }
                 }
             }
         }
      1. Use the Data Access Class:
        Inject the IConfiguration service and use your DataAccess class in a controller or service.
         public class MyController : ControllerBase
         {
             private readonly DataAccess _dataAccess;
      
             public MyController(DataAccess dataAccess)
             {
                 _dataAccess = dataAccess;
             }
      
             [HttpGet]
             public IActionResult Get()
             {
                 _dataAccess.GetData();
                 return Ok();
             }
         }

      2. Using Entity Framework Core

      Entity Framework Core (EF Core) is an Object-Relational Mapper (ORM) that simplifies data access by allowing you to interact with your database using C# objects. .NET Core database connection

      Step-by-Step Guide:

      1. Install the EF Core Packages:
        Add the necessary NuGet packages for EF Core and SQL Server.
         dotnet add package Microsoft.EntityFrameworkCore
         dotnet add package Microsoft.EntityFrameworkCore.SqlServer
      1. Create a DbContext:
        Define a DbContext class to represent your database context.
         using Microsoft.EntityFrameworkCore;
      
         public class AppDbContext : DbContext
         {
             public AppDbContext(DbContextOptions<AppDbContext> options)
                 : base(options)
             {
             }
      
             public DbSet<YourEntity> YourEntities { get; set; }
         }
      
         public class YourEntity
         {
             public int Id { get; set; }
             public string Name { get; set; }
         }
      1. Configure the DbContext in Startup:
        Register your DbContext in the Startup.cs file.
         public class Startup
         {
             public void ConfigureServices(IServiceCollection services)
             {
                 services.AddDbContext<AppDbContext>(options =>
                     options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
                 services.AddControllers();
             }
         }
      1. Perform Database Operations:
        Use dependency injection to access the DbContext and perform CRUD operations.
         public class YourService
         {
             private readonly AppDbContext _context;
      
             public YourService(AppDbContext context)
             {
                 _context = context;
             }
      
             public async Task<List<YourEntity>> GetEntitiesAsync()
             {
                 return await _context.YourEntities.ToListAsync();
             }
         }
      1. Use the Service in a Controller:
        Inject your service and use it in your controller.
         public class YourController : ControllerBase
         {
             private readonly YourService _service;
      
             public YourController(YourService service)
             {
                 _service = service;
             }
      
             [HttpGet]
             public async Task<IActionResult> Get()
             {
                 var entities = await _service.GetEntitiesAsync();
                 return Ok(entities);
             }
         }

      3. Using Dapper

      .NET Core database connection: Dapper is a lightweight ORM that provides a faster alternative to Entity Framework Core by mapping SQL queries to C# objects.

      Step-by-Step Guide:

      1. Install the Dapper Package:
        Add the Dapper NuGet package to your project.
         dotnet add package Dapper
      1. Create a Repository Class:
        Use SqlConnection along with Dapper’s extension methods to execute queries.
         using System.Collections.Generic;
         using System.Data.SqlClient;
         using System.Threading.Tasks;
         using Dapper;
         using Microsoft.Extensions.Configuration;
      
         public class DapperRepository
         {
             private readonly string _connectionString;
      
             public DapperRepository(IConfiguration configuration)
             {
                 _connectionString = configuration.GetConnectionString("DefaultConnection");
             }
      
             public async Task<IEnumerable<YourEntity>> GetEntitiesAsync()
             {
                 using (SqlConnection connection = new SqlConnection(_connectionString))
                 {
                     string query = "SELECT * FROM YourTable";
                     return await connection.QueryAsync<YourEntity>(query);
                 }
             }
         }
      1. Use the Repository:
        Inject your repository into a service or controller to use it.
         public class YourController : ControllerBase
         {
             private readonly DapperRepository _repository;
      
             public YourController(DapperRepository repository)
             {
                 _repository = repository;
             }
      
             [HttpGet]
             public async Task<IActionResult> Get()
             {
                 var entities = await _repository.GetEntitiesAsync();
                 return Ok(entities);
             }
         }

      Conclusion

      .NET Core database connection can be achieved through several methods, each suitable for different scenarios:

      • ADO.NET offers a straightforward and low-level approach, giving you complete control over SQL queries and connection management.
      • Entity Framework Core provides an ORM-based solution with rich features for managing database entities and relationships.
      • Dapper is a high-performance micro-ORM ideal for scenarios where you need a balance between raw SQL and ORM features.

      .NET documentation

      Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
      Previous ArticleLaptop Generations A Comprehensive Guide
      Next Article How to Fix CORS Error in .NET Core: A Step-by-Step Guide
      admin
      • Website
      • Facebook
      • Pinterest
      • LinkedIn

      Welcome to Dastgeertech Studio! We are a dynamic and innovative tech company based in Lahore, Pakistan. At Dastgeertech Studio, we are dedicated to providing cutting-edge technology solutions tailored to meet the unique needs of our clients.

      Related Posts

      Blog

      Best Value Flagship Phones 2026: Top Picks & Reviews

      February 28, 2026
      Read More
      Artificial Intelligence

      AI Won’t Replace Web Developers – But THIS Will Change Everything 2026

      November 29, 2025
      Read More
      Blog

      How to Fix a Slow Loading Website: 2025 Guide for Beginners

      November 29, 2025
      Read More
      Add A Comment

      Leave a ReplyCancel reply

      This site uses Akismet to reduce spam. Learn how your comment data is processed.

      Top Posts

      How to Fix CORS Error in .NET Core: A Step-by-Step Guide

      September 16, 2024172 Views

      aaPanel Free Web Hosting Control Panel Installation on Ubuntu

      August 3, 202462 Views

      Google Pixel 8 & 8 Pro: Unveiling the Latest Android Powerhouse

      June 16, 202435 Views
      Latest Reviews
      Most Popular

      How to Fix CORS Error in .NET Core: A Step-by-Step Guide

      September 16, 2024172 Views

      aaPanel Free Web Hosting Control Panel Installation on Ubuntu

      August 3, 202462 Views

      Google Pixel 8 & 8 Pro: Unveiling the Latest Android Powerhouse

      June 16, 202435 Views
      Our Picks

      5G Advanced 2026: Real Speeds and Coverage You Can Expect Review: Brutally Honest Assessment

      April 18, 2026

      Best Foldable Phones 2026: Samsung Google OnePlus Comparison: The Complete Breakdown Nobody Asked For

      April 17, 2026

      Tech Jobs 2026: Highest Paying Roles and Skills in Demand Review: Brutally Honest Assessment

      April 17, 2026
      © 2016 Dastgeertech Studio. All rights reserved.
      • Dastgeertech Studio
      • Technology
      • Privacy Policy
      • About Us
      • Blog

      Type above and press Enter to search. Press Esc to cancel.

      Ad Blocker Enabled!
      Ad Blocker Enabled!
      Our website is made possible by displaying online advertisements to our visitors. Please support us by disabling your Ad Blocker.

      Sign In or Register

      Welcome Back!

      Login below or Register Now.

      Lost password?

      Register Now!

      Already registered? Login.

      A password will be e-mailed to you.