Tuesday, November 17, 2026

Complete Guide to GitLab: From Beginner to Advanced – End-to-End DevOps Guide

 


Blog Category: DevOps | Git | CI/CD | Cloud | Software Development

Level: Beginner to Advanced
Technology Stack: Git, GitLab, .NET Core, Docker, Kubernetes, Azure DevOps

1. Introduction to GitLab

In modern software development, managing source code, collaborating with developers, automating builds, testing applications, and deploying applications to production are essential activities.

Traditionally, development teams use multiple tools for these activities:

  • Git for source code management.
  • Jenkins for CI/CD automation.
  • SonarQube for code quality analysis.
  • Docker for containerization.
  • Kubernetes for container orchestration.
  • Jira for project management.
  • Separate tools for security scanning and deployment.

GitLab provides an integrated DevSecOps platform that brings many of these capabilities together.

GitLab is a web-based DevOps platform built around Git. It helps development teams manage the complete software development lifecycle, from planning and coding to testing, security, deployment, and monitoring.

Official website: GitLab

Official documentation: GitLab Documentation

What can we do with GitLab?

  1. Create and manage Git repositories.
  2. Manage source code.
  3. Create branches and merge code.
  4. Perform code reviews.
  5. Track bugs and development tasks.
  6. Configure CI/CD pipelines.
  7. Build and test applications automatically.
  8. Integrate SonarQube.
  9. Perform security scanning.
  10. Build Docker images.
  11. Deploy applications to Azure, AWS, or Kubernetes.
  12. Monitor application deployments.

2. Understanding Git vs GitLab

Many developers think Git and GitLab are the same. However, they are different.

GitGitLab
Distributed version control systemDevOps platform
Tracks source code changesManages complete development lifecycle
Works locally on a computerProvides web-based collaboration
Supports branches and commitsProvides merge requests
Supports version historyProvides repository management
Does not provide a built-in CI/CD platformProvides integrated CI/CD
Open-source softwareOffers Free, Premium, and Ultimate offerings

Real-Time Example

Suppose we are developing an ASP.NET Core Web API.

Using Git:

A developer creates a branch, modifies the code, commits changes, and pushes them to a remote repository.

Using GitLab:

The developer pushes code to GitLab, creates a merge request, requests a code review, executes automated pipelines, checks code quality, and deploys the application.

In simple terms:

  • Git manages source code versions.
  • GitLab provides a platform to collaborate, automate, secure, and deliver software.

3. Understanding GitLab Architecture

Before working with GitLab, let's understand its major components.

Important GitLab Components

ComponentDescription
GitLab ServerHosts GitLab application
ProjectContains source code and project resources
RepositoryStores source code and Git history
GroupsOrganize multiple projects
BranchesMaintain separate development versions
CommitsRecord code changes
Merge RequestsReview and merge code
IssuesTrack bugs and tasks
GitLab RunnerExecutes CI/CD jobs
PipelineAutomates build, test, and deployment
Container RegistryStores Docker images
Package RegistryStores application packages
EnvironmentsTrack deployments
ArtifactsStore pipeline outputs

GitLab High-Level Architecture

             Developers
                  |
                  |
            Git Commands
                  |
                  v
          +---------------+
          | GitLab Server |
          +---------------+
                  |
          +-------+-------+
          |               |
          v               v
      Repository       Issues
          |
          |
     Merge Request
          |
          v
      CI/CD Pipeline
          |
          v
     GitLab Runner
          |
    +-----+-------+
    |             |
    v             v
  Build         Testing
    |             |
    +------+------+
           |
           v
      Code Quality
      Security Scan
           |
           v
      Docker Image
           |
           v
       Deployment
           |
     +-----+------+
     |            |
     v            v
    QA          Production

This architecture illustrates how developers can use GitLab to automate the software delivery lifecycle.


4. GitLab Account Creation and Project Setup

Let's start working practically.

Step 1: Create a GitLab Account

  1. Open GitLab Sign Up.
  2. Register an account.
  3. Verify your email address.
  4. Log in to GitLab.

GitLab offers two major deployment options.

1. GitLab.com

  • Cloud-hosted GitLab platform.
  • No need to maintain your own GitLab server.
  • Suitable for individual developers and teams.

2. GitLab Self-Managed

  • Organizations host GitLab on their own infrastructure.
  • Provides administrative control.
  • Organizations manage infrastructure, upgrades, and maintenance.

Step 2: Create a New Project

After logging in:

  1. Navigate to Projects.
  2. Select New Project.
  3. Choose Create Blank Project.
  4. Enter the project name.

Example:

Project Name: EmployeeManagementAPI

Description:
ASP.NET Core Web API for Employee Management.

Visibility:
Private
  1. Initialize the repository with a README file.
  2. Click Create Project.

Your GitLab project is ready.

A project is the central workspace where your team manages source code, issues, merge requests, and CI/CD configurations. GitLab Docs


5. Understanding GitLab Groups and Projects

GitLab provides Groups and Projects to organize development activities.

What is a Group?

A group is a collection of related projects.

For example:

Organization
     |
     v
EmployeeManagement
     |
     +-------------------+
     |                   |
     v                   v
 EmployeeAPI        EmployeeUI
     |
     v
 EmployeeDatabase

A group helps organizations manage:

  • Multiple projects.
  • Team members.
  • Permissions.
  • Shared CI/CD configurations.
  • Project-level organization.

What is a Project?

A project represents an individual application or software product.

Example:

Group: BankingApplications

Projects:
    1. CustomerAPI
    2. AccountAPI
    3. PaymentAPI
    4. NotificationAPI

Each project can maintain its own:

  • Repository.
  • Branches.
  • Merge requests.
  • Issues.
  • Pipelines.
  • CI/CD variables.

6. GitLab User Roles and Permissions

In enterprise projects, different team members have different responsibilities.

GitLab provides roles to control access.

RoleResponsibility
GuestLimited project access
PlannerPlan and manage work where supported
ReporterView project information and issues
DeveloperPush code and create merge requests
MaintainerManage project settings and repositories
OwnerManage group or project ownership, where applicable

Real-Time Example

Consider an enterprise .NET application development team.

Team MemberGitLab Role
Project ManagerPlanner or Reporter
Business AnalystGuest or Planner
.NET DeveloperDeveloper
Tech LeadMaintainer
DevOps EngineerMaintainer
Project OwnerOwner

Best Practice: Follow the principle of least privilege. Give users only the permissions required for their responsibilities.


7. Understanding Git Branching Strategy

Branching is one of the most important concepts in GitLab.

In enterprise projects, multiple developers work on the same application simultaneously.

Instead of modifying the main branch directly, developers create separate branches.

Common Branches

BranchPurpose
mainProduction-ready code
developDevelopment integration
feature/*New functionality
bugfix/*Bug fixes
release/*Release preparation
hotfix/*Urgent production fixes

Example Branch Structure

main
  |
  +---- develop
          |
          +---- feature/employee-create
          |
          +---- feature/employee-update
          |
          +---- bugfix/employee-validation
          |
          +---- release/1.0

Real-Time Development Scenario

Suppose three developers are working on an Employee Management application.

Developer 1:

feature/employee-create

Developer 2:

feature/employee-update

Developer 3:

feature/employee-delete

Each developer works independently.

After development:

  1. Push code to GitLab.
  2. Create a merge request.
  3. Request code review.
  4. Execute CI/CD pipeline.
  5. Get approval.
  6. Merge into the target branch.

This approach helps teams work independently without directly modifying production-ready code.


8. Essential Git Commands for GitLab

Git commands are important for every developer working with GitLab.

8.1 Configure Git

git config --global user.name "Developer"

git config --global user.email "developer@example.com"

8.2 Clone a Repository

Cloning downloads the remote repository to your local machine.

git clone https://gitlab.com/group/project.git

8.3 Navigate to Project

cd EmployeeManagementAPI

8.4 Check Current Branch

git branch

8.5 Create a New Branch

git checkout -b feature/employee-create

Alternatively:

git switch -c feature/employee-create

8.6 Check Modified Files

git status

8.7 Add Files

git add .

8.8 Commit Changes

git commit -m "Added employee creation API"

8.9 Push Changes

git push origin feature/employee-create

8.10 Pull Latest Changes

git pull origin develop

8.11 Fetch Remote Changes

git fetch origin

8.12 Merge Branches

git checkout develop

git merge feature/employee-create

8.13 Delete a Local Branch

git branch -d feature/employee-create

8.14 Delete a Remote Branch

git push origin --delete feature/employee-create

Git Commands Summary

CommandPurpose
git cloneDownload repository
git initInitialize repository
git statusCheck modified files
git addStage changes
git commitSave changes locally
git pushUpload commits
git pullFetch and integrate changes
git fetchDownload remote updates
git mergeMerge branches
git checkoutSwitch branches
git branchList branches
git logView commit history
git stashTemporarily save uncommitted changes
git resetMove HEAD and potentially change staging
git revertCreate a commit that reverses another commit

9. Understanding Merge Requests (MR)

A Merge Request is one of the most important features in GitLab.

A merge request allows developers to propose changes from one branch into another branch.

It supports:

  • Code reviews.
  • Discussion.
  • Approval workflows.
  • Pipeline validation.
  • Change tracking.
  • Merge conflict resolution.

Real-Time Example

Suppose a developer creates:

feature/employee-create

After completing development, the developer pushes the branch.

git push origin feature/employee-create

Now navigate to GitLab.

  1. Open the project.
  2. Navigate to Merge Requests.
  3. Click New Merge Request.
  4. Select source branch.
  5. Select target branch.
  6. Add a title and description.
  7. Assign reviewers.
  8. Create the merge request.

Example:

Source Branch:
feature/employee-create

Target Branch:
develop

Title:
Implemented Employee Creation API

Merge Request Workflow

Developer
    |
    v
Create Feature Branch
    |
    v
Write Code
    |
    v
Commit Changes
    |
    v
Push to GitLab
    |
    v
Create Merge Request
    |
    v
Code Review
    |
    v
Pipeline Validation
    |
    v
Approval
    |
    v
Merge into Develop

What happens during code review?

The reviewer checks:

  1. Coding standards.
  2. Business logic.
  3. SQL query performance.
  4. Exception handling.
  5. Security vulnerabilities.
  6. Duplicate code.
  7. Unit test coverage.
  8. Code complexity.

Important: GitLab can enforce approval requirements and pipeline success before allowing a merge, depending on project configuration. GitLab Docs


10. Understanding GitLab Issues

GitLab Issues help development teams track tasks, bugs, enhancements, and technical activities.

Example

Suppose the Employee API is returning HTTP 500 when creating an employee.

Create an issue:

Issue Title:
Employee API Returning 500 Error

Description:
Employee creation API is failing
when submitting valid employee details.

Priority:
High

Assigned To:
Developer

Labels:
Bug, API, Backend

Common Issue Types

  • Bug.
  • Feature.
  • Enhancement.
  • Technical Debt.
  • Production Issue.
  • Performance Improvement.

Issue Lifecycle

New Issue
    |
    v
Assigned
    |
    v
In Progress
    |
    v
Code Fix
    |
    v
Code Review
    |
    v
Testing
    |
    v
Closed

Issues can also be linked to merge requests so that development activities remain traceable.


11. GitLab CI/CD – Complete Explanation

This is one of the most important sections.

GitLab CI/CD automates the application development and deployment process.

CI/CD stands for:

  • CI – Continuous Integration.
  • CD – Continuous Delivery or Continuous Deployment.

What is Continuous Integration?

Continuous Integration means developers frequently integrate their code changes into a shared repository.

Whenever code is pushed, automated processes can:

  1. Restore dependencies.
  2. Compile the application.
  3. Execute unit tests.
  4. Perform code quality checks.
  5. Generate build artifacts.

What is Continuous Delivery?

Continuous Delivery ensures that successfully validated application builds are ready for deployment.

A production deployment may require manual approval.

What is Continuous Deployment?

Continuous Deployment automatically deploys successfully validated changes to production when the configured conditions are satisfied.

GitLab CI/CD Architecture

Developer Pushes Code
         |
         v
   GitLab Repository
         |
         v
    CI/CD Pipeline
         |
         v
     GitLab Runner
         |
         v
      Build Job
         |
         v
      Test Job
         |
         v
  SonarQube Analysis
         |
         v
   Security Scanning
         |
         v
    Docker Build
         |
         v
   Container Registry
         |
         v
      Deployment
         |
         v
      Production

GitLab CI/CD uses a configuration file called .gitlab-ci.yml. It defines pipeline stages, jobs, scripts, variables, and dependencies. GitLab Docs


12. Understanding GitLab CI/CD Components

Before creating a pipeline, understand these important components.

12.1 Pipeline

A pipeline is a collection of jobs that execute according to defined rules and dependencies.

Example:

Pipeline
   |
   +---- Build
   |
   +---- Test
   |
   +---- Code Quality
   |
   +---- Deploy

12.2 Stages

Stages define the execution sequence.

Example:

stages:
  - build
  - test
  - quality
  - deploy

Stages normally execute sequentially.

12.3 Jobs

Jobs define the actual activities.

Example:

build-job:
  stage: build
  script:
    - echo "Building application"

12.4 Runner

A GitLab Runner is an application that executes CI/CD jobs.

Think of the runner as a worker that receives pipeline jobs and executes the configured commands.

For example:

GitLab Server
      |
      v
Pipeline Created
      |
      v
Job Assigned
      |
      v
GitLab Runner
      |
      v
Execute Commands
      |
      v
Return Job Status

12.5 Artifacts

Artifacts are files generated by pipeline jobs.

Examples:

  • DLL files.
  • ZIP packages.
  • Test reports.
  • Code coverage reports.
  • Build outputs.

12.6 Cache

Cache stores reusable files between pipeline jobs or executions to reduce build time.

Example:

cache:
  paths:
    - .nuget/packages/

Artifacts and cache serve different purposes: artifacts pass job outputs, while caches improve execution efficiency.


13. Create Your First GitLab CI/CD Pipeline

Let's create a simple pipeline.

Step 1: Open Your GitLab Project

Navigate to:

Project
  |
  v
Code
  |
  v
Repository

Step 2: Create a New File

Create:

.gitlab-ci.yml

This file must be placed in the root directory of your repository unless you configure a custom pipeline file.

Step 3: Add the Following YAML

stages:
  - build
  - test
  - deploy

build-job:
  stage: build
  script:
    - echo "Building application"

test-job:
  stage: test
  script:
    - echo "Running unit tests"

deploy-job:
  stage: deploy
  script:
    - echo "Deploying application"

Step 4: Commit the File

Commit the changes to your repository.

GitLab automatically detects the pipeline configuration and can trigger a pipeline based on the configured events.

Step 5: Check Pipeline Execution

Navigate to:

Build
  |
  v
Pipelines

You should see:

Pipeline Status

Build       SUCCESS
Test        SUCCESS
Deploy      SUCCESS

This is your first GitLab CI/CD pipeline.


14. Real-Time GitLab CI/CD Pipeline for .NET 8 Web API

Now let's implement a practical example using an ASP.NET Core Web API.

Project Structure

EmployeeManagementAPI
       |
       +---- Controllers
       |
       +---- Models
       |
       +---- Services
       |
       +---- Data
       |
       +---- EmployeeManagementAPI.csproj
       |
       +---- EmployeeManagementAPI.sln
       |
       +---- .gitlab-ci.yml

Pipeline Requirements

We need to automate:

  1. Restore NuGet packages.
  2. Build the application.
  3. Execute unit tests.
  4. Publish application files.
  5. Deploy to a development environment.

Complete .gitlab-ci.yml

stages:
  - restore
  - build
  - test
  - publish

variables:
  DOTNET_CLI_TELEMETRY_OPTOUT: "1"
  DOTNET_NOLOGO: "true"
  BUILD_CONFIGURATION: "Release"

default:
  image: mcr.microsoft.com/dotnet/sdk:8.0

restore-job:
  stage: restore
  script:
    - dotnet restore EmployeeManagementAPI.sln

build-job:
  stage: build
  script:
    - dotnet build EmployeeManagementAPI.sln
      --configuration $BUILD_CONFIGURATION
      --no-restore

test-job:
  stage: test
  script:
    - dotnet test EmployeeManagementAPI.sln
      --configuration $BUILD_CONFIGURATION
      --no-build

publish-job:
  stage: publish
  script:
    - dotnet publish EmployeeManagementAPI/EmployeeManagementAPI.csproj
      --configuration $BUILD_CONFIGURATION
      --output publish
  artifacts:
    paths:
      - publish/
    expire_in: 1 week

Note: Replace the solution and project paths with your actual repository paths. This example assumes the application targets .NET 8 and has a compatible test project.

Explanation

Restore Stage

dotnet restore

Downloads the required NuGet packages.

Build Stage

dotnet build

Compiles the application and identifies compilation errors.

Test Stage

dotnet test

Executes automated unit tests.

Publish Stage

dotnet publish

Generates application deployment files.

Expected Pipeline Execution

Restore
   |
   v
Build
   |
   v
Test
   |
   v
Publish
   |
   v
Artifacts Generated

15. Integrating SonarQube with GitLab

SonarQube is widely used in enterprise projects to identify code quality issues.

It helps developers identify:

  • Bugs.
  • Code smells.
  • Security vulnerabilities.
  • Duplicated code.
  • Maintainability issues.
  • Code complexity.
  • Test coverage information.

GitLab + SonarQube Architecture

Developer
    |
    v
Push Code to GitLab
    |
    v
GitLab Pipeline
    |
    v
Build Application
    |
    v
SonarQube Scanner
    |
    v
Analyze Source Code
    |
    v
SonarQube Server
    |
    v
Quality Gate
    |
    +----------+
    |          |
    v          v
  Passed     Failed
    |          |
    v          v
 Continue    Fix Issues
 Pipeline       |
                v
             Recheck

Step 1: Configure SonarQube

You need:

  • SonarQube server.
  • SonarQube project.
  • Project key.
  • Authentication token.
  • Scanner compatible with your build environment.

Step 2: Configure GitLab Variables

Navigate to:

Project
  |
  v
Settings
  |
  v
CI/CD
  |
  v
Variables

Add:

SONAR_HOST_URL
SONAR_TOKEN
SONAR_PROJECT_KEY

Protect and mask sensitive variables as appropriate.

Step 3: Configure Pipeline

For a .NET project, an illustrative scanner sequence is:

sonarqube-analysis:
  stage: quality
  script:
    - dotnet tool install --global dotnet-sonarscanner

    - export PATH="$PATH:$HOME/.dotnet/tools"

    - dotnet sonarscanner begin
      /k:"$SONAR_PROJECT_KEY"
      /d:sonar.host.url="$SONAR_HOST_URL"
      /d:sonar.token="$SONAR_TOKEN"

    - dotnet build EmployeeManagementAPI.sln

    - dotnet sonarscanner end
      /d:sonar.token="$SONAR_TOKEN"

Important: In a real pipeline, SonarScanner's begin step must execute before the build, and its end step must execute after the build. Configure the appropriate scanner version and analysis settings for your SonarQube edition.

How to Fix SonarQube Issues?

Suppose SonarQube identifies:

Issue:
Method has high cognitive complexity.

File:
EmployeeService.cs

Severity:
Major

Developer activities:

  1. Open the SonarQube dashboard.
  2. Navigate to the identified issue.
  3. Understand the code quality rule.
  4. Refactor the method.
  5. Commit the changes.
  6. Push the updated code.
  7. Execute the pipeline again.
  8. Verify the new SonarQube analysis.

This helps maintain code quality throughout development.


16. GitLab CI/CD Variables and Secrets Management

In enterprise applications, pipelines require different configuration values.

Examples:

Database Connection String
API URL
Azure Client ID
Azure Client Secret
Docker Registry Credentials
SonarQube Token

Never store sensitive information directly inside .gitlab-ci.yml.

Configure Variables

Navigate to:

Project
  |
  v
Settings
  |
  v
CI/CD
  |
  v
Variables

Create:

VariableExample
DATABASE_URLDatabase endpoint
API_URLAPI endpoint
SONAR_TOKENSonarQube token
AZURE_CLIENT_IDAzure application ID
AZURE_CLIENT_SECRETSecret value

Example YAML:

deploy-job:
  stage: deploy
  script:
    - echo "Deploying application"
    - echo "$API_URL"

For production applications, avoid printing secrets in pipeline logs.

Important Variable Types

Masked Variables: Help prevent variable values from appearing in logs.

Protected Variables: Restrict access to pipelines running on protected branches or tags.

Environment-scoped Variables: Allow different values for development, QA, and production environments.

GitLab supports project, group, and instance-level CI/CD variables. GitLab Docs


17. GitLab Docker Integration

Docker is widely used in modern application deployments.

GitLab supports container image building and provides a Container Registry to store images.

Architecture

.NET Application
       |
       v
Dockerfile
       |
       v
Docker Build
       |
       v
Docker Image
       |
       v
GitLab Container Registry
       |
       v
Kubernetes / Azure
       |
       v
Running Application

Example Dockerfile for .NET 8

FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS runtime

WORKDIR /app

EXPOSE 8080

COPY publish/ .

ENTRYPOINT ["dotnet", "EmployeeManagementAPI.dll"]

This example expects the publish directory to be available in the Docker build context.

Docker Build Command

docker build -t employee-api:1.0 .

Run Container

docker run -d -p 8080:8080 employee-api:1.0

GitLab Container Registry

Navigate to:

Project
  |
  v
Deploy
  |
  v
Container Registry

The registry stores Docker images generated through CI/CD pipelines.


18. GitLab CI/CD Pipeline for Docker Build

Example:

stages:
  - build
  - docker

build-job:
  stage: build
  image: mcr.microsoft.com/dotnet/sdk:8.0
  script:
    - dotnet restore
    - dotnet publish -c Release -o publish
  artifacts:
    paths:
      - publish/

docker-build:
  stage: docker
  image: docker:cli
  services:
    - name: docker:dind
      alias: docker
  variables:
    DOCKER_HOST: tcp://docker:2376
    DOCKER_TLS_CERTDIR: "/certs"
  script:
    - echo "$CI_REGISTRY_PASSWORD" |
      docker login "$CI_REGISTRY"
      -u "$CI_REGISTRY_USER" --password-stdin

    - docker build -t "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA" .

    - docker push "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA"

Note: This is an illustrative Docker-in-Docker configuration. Your runner must support the required service and networking configuration. For production, consider rootless BuildKit or another approved image-building approach to reduce privileged runner requirements.


19. GitLab Deployment to Azure Kubernetes Service (AKS)

Let's understand how GitLab can deploy a containerized .NET application to Azure Kubernetes Service.

Architecture

Developer
    |
    v
GitLab Repository
    |
    v
GitLab Pipeline
    |
    v
.NET Build
    |
    v
Unit Testing
    |
    v
SonarQube
    |
    v
Docker Build
    |
    v
GitLab Container Registry
    |
    v
Azure Container Registry
    |
    v
Azure Kubernetes Service
    |
    v
Application Running

Deployment Steps

  1. Create an AKS cluster.
  2. Configure Azure Container Registry.
  3. Build the Docker image.
  4. Push the image to the registry.
  5. Configure secure Azure authentication for GitLab.
  6. Connect the deployment job to AKS.
  7. Apply Kubernetes deployment manifests.
  8. Verify application health.

Kubernetes Deployment YAML

Create:

deployment.yaml

apiVersion: apps/v1
kind: Deployment

metadata:
  name: employee-api

spec:
  replicas: 2

  selector:
    matchLabels:
      app: employee-api

  template:
    metadata:
      labels:
        app: employee-api

    spec:
      containers:
        - name: employee-api

          image: myregistry.azurecr.io/employee-api:latest

          ports:
            - containerPort: 8080

Kubernetes Service YAML

Create:

service.yaml

apiVersion: v1
kind: Service

metadata:
  name: employee-api-service

spec:
  type: ClusterIP

  selector:
    app: employee-api

  ports:
    - port: 80
      targetPort: 8080

Deploy to AKS

Once authentication and Kubernetes context are configured:

kubectl apply -f deployment.yaml

kubectl apply -f service.yaml

Check deployment:

kubectl get deployments

Check pods:

kubectl get pods

Check services:

kubectl get services

For production, use immutable image tags rather than relying on latest, and configure appropriate resource requests, limits, health probes, and deployment permissions.


20. GitLab Environments – Development, QA, UAT, Production

Enterprise applications typically have multiple deployment environments.

EnvironmentPurpose
DevelopmentDeveloper testing
QAFunctional testing
SITSystem integration testing
UATBusiness acceptance testing
StagingProduction-like validation
ProductionLive application

Environment Deployment Flow

GitLab Pipeline
      |
      v
Development
      |
      v
QA
      |
      v
SIT
      |
      v
UAT
      |
      v
Production

Example GitLab Deployment Job

deploy-development:
  stage: deploy
  script:
    - echo "Deploying to Development"
  environment:
    name: development
  rules:
    - if: '$CI_COMMIT_BRANCH == "develop"'

Production deployment should be protected and should require appropriate authorization.

GitLab environments help track deployments, while protected environments and deployment approvals can restrict production access. GitLab Docs


21. GitLab Security and DevSecOps

Security is an important part of enterprise application development.

GitLab provides security capabilities that can be integrated into CI/CD workflows.

Important Security Scanning Types

Security ScanPurpose
SASTIdentify source code security issues
DASTTest running applications for vulnerabilities
Dependency ScanningIdentify vulnerable dependencies
Secret DetectionDetect exposed secrets
Container ScanningIdentify container image vulnerabilities
IaC ScanningIdentify infrastructure configuration issues

DevSecOps Workflow

Plan
  |
  v
Code
  |
  v
Build
  |
  v
Test
  |
  v
Security Scanning
  |
  v
Package
  |
  v
Deploy
  |
  v
Monitor

Example Security Configuration

GitLab provides security templates that can be included in CI/CD configuration.

For example:

include:
  - template: Jobs/SAST.gitlab-ci.yml

The exact available templates and features depend on your GitLab version and subscription tier.

Security findings should be reviewed and addressed according to your organization's security policies.


22. GitLab Pipeline Troubleshooting

As a developer or DevOps engineer, troubleshooting pipeline failures is an essential responsibility.

Let's understand common issues.

Issue 1: Pipeline Failed

Possible reasons:

  • Compilation errors.
  • Missing dependencies.
  • Incorrect YAML configuration.
  • Runner unavailable.
  • Environment configuration problems.

How to troubleshoot:

  1. Open the GitLab project.
  2. Navigate to Build → Pipelines.
  3. Open the failed pipeline.
  4. Select the failed job.
  5. Review the job logs.
  6. Identify the failing command.
  7. Fix the issue and rerun the pipeline.

Issue 2: GitLab Runner Not Available

Error:

This job is stuck because there are no runners available.

Possible reasons:

  • No runner registered.
  • Runner is offline.
  • Runner tags do not match.
  • Runner is not allowed to execute the job.

Solution:

Check:

Project
  |
  v
Settings
  |
  v
CI/CD
  |
  v
Runners

Issue 3: Docker Build Failed

Possible reasons:

  • Dockerfile missing.
  • Invalid Docker syntax.
  • Registry authentication failure.
  • Docker daemon unavailable.
  • Insufficient disk space.

Check Docker build logs and runner configuration.

Issue 4: Deployment Failed

Possible reasons:

  • Invalid Kubernetes credentials.
  • Incorrect cluster endpoint.
  • Image unavailable.
  • Insufficient deployment permissions.
  • Invalid Kubernetes YAML.

Useful commands:

kubectl get pods

kubectl describe pod employee-api

kubectl get events

kubectl logs deployment/employee-api

Issue 5: Merge Request Pipeline Failed

Possible reasons:

  • Unit tests failed.
  • Code quality checks failed.
  • Security scanning identified blocking issues.
  • Build errors.

Review the failed job before merging.


23. GitLab Integration with Other Tools

GitLab can integrate with several tools used in enterprise software development.

ToolIntegration Purpose
SonarQubeCode quality analysis
DockerContainerization
KubernetesContainer orchestration
AzureCloud infrastructure
AWSCloud infrastructure
JiraProject management
SlackTeam notifications
TerraformInfrastructure as Code
NuGetPackage management
PrometheusMetrics monitoring
GrafanaMonitoring dashboards

These integrations help organizations establish automated development and deployment workflows.


24. GitLab Best Practices for Enterprise Projects

Following best practices improves maintainability, security, and deployment reliability.

Source Code Management

  1. Follow a consistent branching strategy.
  2. Never push directly to protected production branches unless explicitly permitted.
  3. Use meaningful commit messages.
  4. Keep feature branches small.
  5. Remove merged branches when appropriate.

Merge Requests

  1. Require code reviews.
  2. Link merge requests to relevant issues.
  3. Require successful pipelines.
  4. Follow approval policies.
  5. Review code quality and security findings.

CI/CD

  1. Keep pipeline configuration maintainable.
  2. Use reusable templates.
  3. Avoid unnecessary pipeline executions.
  4. Store important build outputs as artifacts.
  5. Use caching appropriately.
  6. Separate build and deployment responsibilities.

Security

  1. Never hardcode passwords.
  2. Use protected and masked variables.
  3. Restrict production deployment permissions.
  4. Scan dependencies.
  5. Scan container images.
  6. Rotate credentials according to organizational policy.

Production Deployment

  1. Use immutable image tags.
  2. Maintain deployment history.
  3. Validate application health.
  4. Implement rollback procedures.
  5. Monitor application logs and metrics.

25. Real-Time Enterprise Project Example

Let's combine everything into one practical scenario.

Suppose an organization is developing an Employee Management System using:

Backend: ASP.NET Core Web API
Frontend: Angular
Database: Azure SQL Database
Repository: GitLab
Code Quality: SonarQube
Containerization: Docker
Orchestration: Azure Kubernetes Service
Cloud: Microsoft Azure

Complete Development Workflow

Step 1: Project Creation

The DevOps engineer creates a GitLab group:

EmployeeManagement

Projects:

EmployeeAPI
EmployeeUI
EmployeeDatabase

Step 2: Developer Creates a Branch

git checkout -b feature/employee-create

Step 3: Developer Implements API

Example:

[ApiController]
[Route("api/[controller]")]
public class EmployeeController : ControllerBase
{
    [HttpPost]
    public IActionResult CreateEmployee(Employee employee)
    {
        if (employee == null)
        {
            return BadRequest();
        }

        return Ok("Employee created successfully");
    }
}

Step 4: Commit and Push Code

git add .

git commit -m "Implemented employee creation API"

git push origin feature/employee-create

Step 5: Create Merge Request

The developer creates a merge request targeting the develop branch.

Step 6: Automated Pipeline

GitLab executes:

Restore
  |
  v
Build
  |
  v
Unit Testing
  |
  v
SonarQube
  |
  v
Security Scan
  |
  v
Docker Build

Step 7: Code Review

The team lead reviews the code and approves the merge request according to project policies.

Step 8: Merge Code

The feature branch is merged into develop.

Step 9: Deployment

The application is deployed to the development environment.

Step 10: QA Validation

The QA team performs functional and integration testing.

Step 11: Production Deployment

After the required approvals, the application is deployed to AKS.

Step 12: Monitoring

The team monitors:

  • Application availability.
  • API response time.
  • HTTP errors.
  • Container health.
  • CPU and memory consumption.
  • Application logs.

This is a practical example of using GitLab throughout an enterprise software delivery lifecycle.


26. GitLab vs GitHub vs Azure DevOps

These three platforms are commonly used in enterprise organizations.

FeatureGitLabGitHubAzure DevOps
Git RepositoryYesYesYes
Branch ManagementYesYesYes
Merge Requests / Pull RequestsMerge RequestsPull RequestsPull Requests
CI/CDGitLab CI/CDGitHub ActionsAzure Pipelines
Code ReviewYesYesYes
Issue TrackingYesYesYes
Container RegistryYesGitHub Container RegistryAzure Container Registry integration
Security ScanningYesYesAvailable through integrations and security services
Kubernetes IntegrationYesYesYes
Cloud IntegrationMultiple cloudsMultiple cloudsStrong Azure integration

Which One Should We Choose?

GitLab:

Suitable for organizations looking for an integrated DevSecOps platform with source code management and CI/CD.

GitHub:

Suitable for organizations that prioritize Git-based collaboration, open-source development, and GitHub Actions.

Azure DevOps:

Suitable for organizations using Azure Boards, Azure Repos, Azure Pipelines, and Microsoft development ecosystems.

The right choice depends on organizational requirements, existing infrastructure, security policies, and licensing.


27. Important GitLab Interview Questions and Answers

Here are some commonly asked GitLab interview questions.

1. What is GitLab?

GitLab is a DevOps platform that provides source code management, collaboration, CI/CD automation, security scanning, and deployment capabilities.

2. What is the difference between Git and GitLab?

Git is a distributed version control system, whereas GitLab is a platform built around Git that provides repository hosting and DevOps capabilities.

3. What is a GitLab Runner?

A GitLab Runner is an application that executes CI/CD jobs defined in a GitLab pipeline.

4. What is .gitlab-ci.yml?

It is a YAML configuration file that defines pipeline stages, jobs, scripts, variables, and execution rules.

5. What is a GitLab pipeline?

A pipeline is a collection of automated jobs that build, test, validate, and deploy an application.

6. What is a GitLab Merge Request?

A merge request allows developers to propose changes from one branch into another branch after code review and validation.

7. What is the difference between a pipeline and a job?

A pipeline contains multiple jobs. A job represents an individual task such as building, testing, or deploying an application.

8. What is a GitLab artifact?

An artifact is a file or collection of files generated by a pipeline job and stored for later use or download.

9. What is the difference between cache and artifacts?

Cache improves pipeline performance by reusing files, whereas artifacts preserve job outputs for later stages or downloads.

10. How do you configure environment-specific variables?

Use GitLab CI/CD variables with appropriate environment scopes.

11. How do you restrict production deployment?

Configure protected branches, protected environments, deployment approvals, and appropriate permissions.

12. What happens when a pipeline fails?

The failed job is marked as failed, and dependent jobs generally do not execute unless configured otherwise.

13. How do you integrate SonarQube with GitLab?

Configure the SonarQube server, project credentials, and scanner in the GitLab CI/CD pipeline.

14. What is GitLab Container Registry?

It is a registry used to store and manage Docker and OCI container images.

15. What is the difference between GitLab.com and GitLab Self-Managed?

GitLab.com is hosted and maintained by GitLab, whereas Self-Managed allows organizations to host and administer their own GitLab instance.


28. Important GitLab Commands Cheat Sheet

CommandDescription
git clone <url>Clone repository
git initInitialize repository
git statusCheck repository status
git add .Stage changes
git commit -m "message"Commit changes
git push origin branchPush branch
git pull origin branchPull branch changes
git fetch originFetch remote changes
git branchList branches
git checkout -b branchCreate branch
git switch branchSwitch branch
git merge branchMerge branch
git logView commit history
git stashTemporarily save changes
git cherry-pick <commit>Apply a specific commit
git revert <commit>Reverse a commit
git remote -vView remote repositories

29. Advantages and Disadvantages of GitLab

Advantages

  1. Integrated DevOps platform.
  2. Built-in CI/CD capabilities.
  3. Source code version control.
  4. Automated application builds.
  5. Merge request-based code reviews.
  6. Security scanning capabilities.
  7. Docker and Kubernetes integrations.
  8. Project management features.
  9. Supports cloud and self-managed deployments.
  10. Automation across the software development lifecycle.

Disadvantages

  1. Advanced features may require paid subscriptions.
  2. Self-managed installations require infrastructure maintenance.
  3. Complex pipelines require YAML knowledge.
  4. Runner configuration can require DevOps expertise.
  5. Large pipelines can consume significant computing resources.
  6. Enterprise implementations require proper security and permission management.

30. Conclusion

GitLab is more than a source code repository management platform. It provides an integrated environment for managing the complete software development lifecycle.

From creating repositories and managing branches to implementing merge requests, automating builds, integrating SonarQube, building Docker images, and deploying applications to Kubernetes, GitLab helps organizations streamline their DevOps processes.

For .NET developers, understanding GitLab CI/CD is particularly valuable because it enables automation of application restoration, compilation, unit testing, code quality validation, packaging, and deployment.

For DevOps engineers, GitLab provides capabilities to implement automated deployment workflows, manage infrastructure integrations, and establish DevSecOps practices.

The most important takeaway is that GitLab helps connect development, testing, security, and operations into one continuous software delivery workflow.


Official GitLab Learning Resources

For additional learning, refer to these official resources:

  1. GitLab Documentation
  2. GitLab CI/CD Documentation
  3. GitLab First Pipeline Tutorial
  4. GitLab Project Management
  5. GitLab Deployment Documentation

Suggested Blog SEO Details

SEO ElementContent
SEO TitleComplete Guide to GitLab: From Beginner to Advanced
Focus KeywordGitLab Tutorial
Secondary KeywordsGitLab CI/CD, GitLab Pipeline, GitLab Runner, GitLab DevOps
CategoryDevOps
Suggested URL Slugcomplete-guide-to-gitlab
Meta DescriptionLearn GitLab from scratch with this end-to-end guide covering Git repositories, branching, merge requests, CI/CD pipelines, SonarQube, Docker, Kubernetes, and Azure deployment.
TagsGitLab, Git, DevOps, CI/CD, Docker, Kubernetes, SonarQube, Azure

Suggested next article: Complete Guide to GitLab CI/CD Pipeline for ASP.NET Core Applications with SonarQube, Docker, and AKS – Real-Time Enterprise Implementation.

Tuesday, September 22, 2026

Dapper vs Entity Framework Core in .NET – Complete End-to-End Guide


Introduction

When developing modern ASP.NET Core Web API applications, one of the most important decisions is how the application communicates with the database.

Two popular approaches in the .NET ecosystem are:

  • Entity Framework Core (EF Core)

  • Dapper

Both are powerful, but they solve the database-access problem differently.

EF Core is a full-featured Object-Relational Mapper (ORM), while Dapper is a lightweight micro-ORM that provides a thin layer over ADO.NET.

A common interview question is:

"What is the difference between Dapper and Entity Framework Core, and when would you use each?"

This article explains the differences from beginner to production level.


1. What is Entity Framework Core?

Entity Framework Core (EF Core) is Microsoft's modern, cross-platform ORM for .NET.

ORM stands for:

Object Relational Mapping

It allows developers to work with database tables using C# classes and LINQ instead of writing SQL for every operation.

For example, suppose we have a database table:

CREATE TABLE Employees
(
    Id INT PRIMARY KEY IDENTITY,
    Name NVARCHAR(100),
    Department NVARCHAR(100),
    Salary DECIMAL(18,2)
);

In EF Core, we can create:

public class Employee
{
    public int Id { get; set; }

    public string Name { get; set; }

    public string Department { get; set; }

    public decimal Salary { get; set; }
}

Then query the database using LINQ:

var employees = await dbContext.Employees
    .Where(x => x.Department == "IT")
    .ToListAsync();

EF Core generates the appropriate SQL behind the scenes.


2. What is Dapper?

Dapper is a lightweight micro-ORM for .NET.

It was originally created by the Stack Overflow team and is widely used for high-performance database access.

Unlike EF Core, Dapper does not attempt to provide a complete ORM framework.

You normally write the SQL yourself:

var sql = """
          SELECT Id, Name, Department, Salary
          FROM Employees
          WHERE Department = @Department
          """;

var employees = await connection.QueryAsync<Employee>(
    sql,
    new { Department = "IT" });

Dapper executes the SQL and maps the returned rows to the Employee C# class.


3. Dapper vs EF Core – High-Level Difference

FeatureDapperEF Core
TypeMicro ORMFull ORM
SQLDeveloper writes SQLEF can generate SQL
LINQLimited/direct SQL approachExtensive LINQ support
Change TrackingNo built-in change trackerYes
MigrationsNoYes
RelationshipsManual SQL/mappingBuilt-in relationship mapping
Lazy LoadingNo built-in ORM-style lazy loadingSupported with configuration
PerformanceGenerally very fastGenerally good, but more abstraction
Control over SQLVery highMedium/High
Learning CurveRelatively lowHigher
CRUDSQL-basedObject-based/LINQ
TransactionsADO.NET transactionsDbContext transactions
Complex queriesExcellent when SQL is knownExcellent with LINQ, but SQL knowledge still useful
Stored ProceduresExcellentSupported
Change TrackingNoYes
Database-firstManualSupported
Code-firstNo EF-style migrationsSupported
Best suited forSQL-centric/high-performance applicationsDomain/application-centric applications

4. Architecture Difference

The biggest conceptual difference is the abstraction level.

Dapper

Application
     |
     v
Repository
     |
     v
Dapper
     |
     v
ADO.NET
     |
     v
SQL Server

You control the SQL.


EF Core

Application
     |
     v
Repository / Service
     |
     v
DbContext
     |
     v
EF Core
     |
     v
LINQ
     |
     v
SQL Generation
     |
     v
SQL Server

EF Core provides more abstraction.


5. Basic EF Core Setup

Suppose we are developing:

ASP.NET Core Web API
        |
        v
EmployeeService
        |
        v
EmployeeRepository
        |
        v
EF Core
        |
        v
Azure SQL / SQL Server

Install the SQL Server provider:

dotnet add package Microsoft.EntityFrameworkCore.SqlServer

For migrations:

dotnet add package Microsoft.EntityFrameworkCore.Tools

6. Create DbContext

public class EmployeeDbContext : DbContext
{
    public EmployeeDbContext(
        DbContextOptions<EmployeeDbContext> options)
        : base(options)
    {
    }

    public DbSet<Employee> Employees { get; set; }
}

7. Configure Connection String

{
  "ConnectionStrings": {
    "DefaultConnection":
      "Server=localhost;Database=EmployeeDb;Trusted_Connection=True;TrustServerCertificate=True"
  }
}

Register DbContext:

builder.Services.AddDbContext<EmployeeDbContext>(options =>
    options.UseSqlServer(
        builder.Configuration.GetConnectionString("DefaultConnection")));

8. EF Core CRUD Operations

Create

var employee = new Employee
{
    Name = "John",
    Department = "IT",
    Salary = 75000
};

dbContext.Employees.Add(employee);

await dbContext.SaveChangesAsync();

EF Core generates an INSERT statement.


9. Read

var employee = await dbContext.Employees
    .FirstOrDefaultAsync(x => x.Id == 10);

10. Read Multiple Records

var employees = await dbContext.Employees
    .Where(x => x.Department == "IT")
    .ToListAsync();

11. Update

var employee = await dbContext.Employees
    .FirstOrDefaultAsync(x => x.Id == 10);

if (employee != null)
{
    employee.Salary = 85000;

    await dbContext.SaveChangesAsync();
}

EF Core detects the modified property using change tracking.


12. Delete

var employee = await dbContext.Employees
    .FindAsync(10);

if (employee != null)
{
    dbContext.Employees.Remove(employee);

    await dbContext.SaveChangesAsync();
}

13. Dapper Setup

Install Dapper:

dotnet add package Dapper

For SQL Server:

dotnet add package Microsoft.Data.SqlClient

14. Dapper Connection

using Microsoft.Data.SqlClient;
using System.Data;

public class EmployeeRepository
{
    private readonly string _connectionString;

    public EmployeeRepository(IConfiguration configuration)
    {
        _connectionString =
            configuration.GetConnectionString("DefaultConnection")!;
    }

    private IDbConnection CreateConnection()
    {
        return new SqlConnection(_connectionString);
    }
}

15. Dapper SELECT

public async Task<IEnumerable<Employee>> GetEmployeesAsync()
{
    using var connection = CreateConnection();

    const string sql = """
        SELECT Id, Name, Department, Salary
        FROM Employees
        """;

    return await connection.QueryAsync<Employee>(sql);
}

16. Dapper SELECT By ID

public async Task<Employee?> GetEmployeeAsync(int id)
{
    using var connection = CreateConnection();

    const string sql = """
        SELECT Id, Name, Department, Salary
        FROM Employees
        WHERE Id = @Id
        """;

    return await connection.QuerySingleOrDefaultAsync<Employee>(
        sql,
        new { Id = id });
}

Notice:

WHERE Id = @Id

and:

new { Id = id }

Dapper maps the parameter safely.


17. Dapper INSERT

public async Task<int> CreateEmployeeAsync(Employee employee)
{
    using var connection = CreateConnection();

    const string sql = """
        INSERT INTO Employees
        (
            Name,
            Department,
            Salary
        )
        VALUES
        (
            @Name,
            @Department,
            @Salary
        );

        SELECT CAST(SCOPE_IDENTITY() AS INT);
        """;

    return await connection.ExecuteScalarAsync<int>(
        sql,
        employee);
}

18. Dapper UPDATE

public async Task<int> UpdateEmployeeAsync(Employee employee)
{
    using var connection = CreateConnection();

    const string sql = """
        UPDATE Employees
        SET
            Name = @Name,
            Department = @Department,
            Salary = @Salary
        WHERE Id = @Id
        """;

    return await connection.ExecuteAsync(sql, employee);
}

19. Dapper DELETE

public async Task<int> DeleteEmployeeAsync(int id)
{
    using var connection = CreateConnection();

    const string sql = """
        DELETE FROM Employees
        WHERE Id = @Id
        """;

    return await connection.ExecuteAsync(
        sql,
        new { Id = id });
}

20. Query vs Execute in Dapper

This is an important interview topic.

Query

Use Query when you expect rows back.

var employees =
    await connection.QueryAsync<Employee>(sql);

Execute

Use Execute for INSERT, UPDATE, DELETE.

var affectedRows =
    await connection.ExecuteAsync(sql);

ExecuteScalar

Use when you want one value.

var employeeId =
    await connection.ExecuteScalarAsync<int>(sql);

21. Entity Framework Core Change Tracking

One of EF Core's major features is change tracking.

For example:

var employee =
    await dbContext.Employees
        .FirstAsync(x => x.Id == 10);

employee.Salary = 100000;

await dbContext.SaveChangesAsync();

EF Core knows that Salary changed.

It generates the UPDATE statement.


22. Dapper Does Not Track Changes

Dapper does not maintain an entity state.

For example:

var employee = await connection.QuerySingleAsync<Employee>(
    sql,
    new { Id = 10 });

employee.Salary = 100000;

Nothing happens automatically.

You must execute an UPDATE yourself:

await connection.ExecuteAsync(
    updateSql,
    employee);

23. AsNoTracking in EF Core

When you only need to read data, change tracking may not be required.

Use:

var employees = await dbContext.Employees
    .AsNoTracking()
    .ToListAsync();

This can reduce tracking overhead for read-only queries.

This is especially useful in:

Reporting
Dashboards
Search APIs
Read-only endpoints
Large result sets

24. Relationships in EF Core

Suppose we have:

Department
    |
    +---- Employee
    +---- Employee
    +---- Employee

Entities:

public class Department
{
    public int Id { get; set; }

    public string Name { get; set; }

    public ICollection<Employee> Employees { get; set; }
        = new List<Employee>();
}

Employee:

public class Employee
{
    public int Id { get; set; }

    public string Name { get; set; }

    public int DepartmentId { get; set; }

    public Department Department { get; set; }
}

EF Core can configure the relationship.

modelBuilder.Entity<Employee>()
    .HasOne(e => e.Department)
    .WithMany(d => d.Employees)
    .HasForeignKey(e => e.DepartmentId);

25. Dapper Relationships

Dapper doesn't automatically manage relationships like EF Core.

You normally write SQL joins.

SELECT
    e.Id,
    e.Name,
    d.Id,
    d.Name
FROM Employees e
INNER JOIN Departments d
    ON e.DepartmentId = d.Id

Then map the result manually using Dapper's multi-mapping capabilities or project into DTOs.


26. EF Core Include

EF Core provides Include.

var employees = await dbContext.Employees
    .Include(x => x.Department)
    .ToListAsync();

This tells EF Core to load the related department data.


27. Dapper Stored Procedures

Dapper works very well with stored procedures.

Example:

CREATE PROCEDURE GetEmployeesByDepartment
    @Department NVARCHAR(100)
AS
BEGIN
    SELECT
        Id,
        Name,
        Department,
        Salary
    FROM Employees
    WHERE Department = @Department;
END

Dapper:

var employees =
    await connection.QueryAsync<Employee>(
        "GetEmployeesByDepartment",
        new
        {
            Department = "IT"
        },
        commandType: CommandType.StoredProcedure);

28. EF Core Stored Procedures

EF Core can also execute stored procedures.

For example, raw SQL can be used:

var employees =
    await dbContext.Employees
        .FromSqlInterpolated(
            $"EXEC GetEmployeesByDepartment {"IT"}")
        .ToListAsync();

EF Core also provides APIs for executing SQL commands where appropriate.

The important point is:

Choosing EF Core does not mean you can never use SQL or stored procedures.


29. SQL Injection

Both Dapper and EF Core can be used safely.

The important thing is parameterization.

Dapper

const string sql = """
    SELECT *
    FROM Employees
    WHERE Department = @Department
    """;

var employees = await connection.QueryAsync<Employee>(
    sql,
    new { Department = department });

Avoid building SQL using string concatenation:

var sql =
    "SELECT * FROM Employees WHERE Department = '" +
    department +
    "'";

30. EF Core Parameterization

LINQ queries are parameterized by EF Core.

var employees = await dbContext.Employees
    .Where(x => x.Department == department)
    .ToListAsync();

EF Core generates parameterized SQL.


31. Transactions with Dapper

Dapper uses ADO.NET transactions.

using var connection = CreateConnection();

connection.Open();

using var transaction = connection.BeginTransaction();

try
{
    await connection.ExecuteAsync(
        insertEmployeeSql,
        employee,
        transaction);

    await connection.ExecuteAsync(
        updateDepartmentSql,
        department,
        transaction);

    transaction.Commit();
}
catch
{
    transaction.Rollback();
    throw;
}

32. Transactions with EF Core

EF Core provides transaction support through Database.

await using var transaction =
    await dbContext.Database.BeginTransactionAsync();

try
{
    dbContext.Employees.Add(employee);

    await dbContext.SaveChangesAsync();

    department.Budget += 1000;

    await dbContext.SaveChangesAsync();

    await transaction.CommitAsync();
}
catch
{
    await transaction.RollbackAsync();
    throw;
}

33. EF Core Migrations

One of the major advantages of EF Core is migrations.

For example:

dotnet ef migrations add InitialCreate

Then:

dotnet ef database update

If you add a property:

public string Email { get; set; }

you can create another migration:

dotnet ef migrations add AddEmployeeEmail

Then:

dotnet ef database update

EF Core manages schema changes through migrations.


34. Does Dapper Support Migrations?

No.

Dapper itself is not a database schema migration framework.

You can use tools such as:

  • SQL scripts

  • DbUp

  • FluentMigrator

  • Flyway

  • Liquibase

  • CI/CD database migration processes

For example:

Application
    |
    +---- Dapper
    |
    +---- SQL Scripts
    |
    +---- Migration Tool
    |
    v
SQL Server

35. Performance Comparison

A common misconception is:

"Dapper is always faster than EF Core."

That is too simplistic.

Dapper has a smaller abstraction layer and often performs very well for straightforward SQL queries.

EF Core has additional capabilities such as:

  • Change tracking

  • Identity resolution

  • LINQ translation

  • Relationship handling

  • Model metadata

  • State management

These features have overhead.

However, properly written EF Core queries can perform very well.

For example:

var employees = await dbContext.Employees
    .AsNoTracking()
    .Where(x => x.Department == "IT")
    .Select(x => new EmployeeDto
    {
        Id = x.Id,
        Name = x.Name
    })
    .ToListAsync();

This avoids retrieving unnecessary columns and avoids tracking.


36. Performance Depends on SQL and Database Design

Database performance is not determined only by Dapper or EF Core.

Other factors include:

Indexes
Query design
Execution plan
Database schema
Network latency
Connection pooling
Number of records
Pagination
Locking
Blocking
CPU
Memory
I/O
Database configuration

For example, a poorly written Dapper query can be slower than a well-written EF Core query.


37. Pagination with Dapper

const string sql = """
    SELECT Id, Name, Department, Salary
    FROM Employees
    ORDER BY Id
    OFFSET @Offset ROWS
    FETCH NEXT @PageSize ROWS ONLY
    """;

var employees = await connection.QueryAsync<Employee>(
    sql,
    new
    {
        Offset = (pageNumber - 1) * pageSize,
        PageSize = pageSize
    });

38. Pagination with EF Core

var employees = await dbContext.Employees
    .AsNoTracking()
    .OrderBy(x => x.Id)
    .Skip((pageNumber - 1) * pageSize)
    .Take(pageSize)
    .ToListAsync();

39. Repository Pattern with EF Core

public interface IEmployeeRepository
{
    Task<Employee?> GetByIdAsync(int id);

    Task<IEnumerable<Employee>> GetAllAsync();

    Task AddAsync(Employee employee);

    Task UpdateAsync(Employee employee);

    Task DeleteAsync(int id);
}

Implementation:

public class EmployeeRepository : IEmployeeRepository
{
    private readonly EmployeeDbContext _context;

    public EmployeeRepository(EmployeeDbContext context)
    {
        _context = context;
    }

    public async Task<Employee?> GetByIdAsync(int id)
    {
        return await _context.Employees
            .FirstOrDefaultAsync(x => x.Id == id);
    }
}

40. Repository Pattern with Dapper

public class EmployeeRepository : IEmployeeRepository
{
    private readonly string _connectionString;

    public EmployeeRepository(IConfiguration configuration)
    {
        _connectionString =
            configuration.GetConnectionString("DefaultConnection")!;
    }

    public async Task<Employee?> GetByIdAsync(int id)
    {
        using var connection =
            new SqlConnection(_connectionString);

        const string sql = """
            SELECT Id, Name, Department, Salary
            FROM Employees
            WHERE Id = @Id
            """;

        return await connection.QuerySingleOrDefaultAsync<Employee>(
            sql,
            new { Id = id });
    }
}

41. CQRS with Dapper and EF Core

A very common enterprise architecture is:

                 API
                  |
             Application
                  |
             +----+----+
             |         |
         Commands    Queries
             |         |
             v         v
          EF Core    Dapper
             |         |
             v         v
          Database   Database

For example:

Command

Create employee:

POST /employees
       |
       v
Command Handler
       |
       v
EF Core
       |
       v
SQL Server

Query

Get employees:

GET /employees
       |
       v
Query Handler
       |
       v
Dapper
       |
       v
SQL Server

This approach can combine the strengths of both technologies.


42. Real-Time Enterprise Example

Consider a BPO workforce-management application.

The system contains:

Forecast Service
Workforce Service
Capacity Service
Hiring Service
Employee Service
Reporting Service

Suppose the Reporting Service needs a complicated dashboard query:

Employee
    |
Department
    |
Skill
    |
Shift
    |
Forecast
    |
Actual Volume
    |
Utilization

The query may involve:

  • Multiple JOINs

  • Aggregations

  • Window functions

  • CTEs

  • Stored procedures

  • Complex filtering

Dapper can be a strong choice when the team wants precise control over the SQL.

For standard application CRUD, EF Core may provide faster development.

Therefore:

CRUD / Domain Logic
       |
     EF Core

Complex Reporting
       |
     Dapper

This is a hybrid approach.


43. Can We Use Dapper and EF Core in the Same Application?

Yes.

There is no requirement to choose only one.

For example:

ASP.NET Core API
       |
       +----------------+
       |                |
   EF Core           Dapper
       |                |
       +-------+--------+
               |
          SQL Server

Use EF Core for:

Create
Update
Delete
Domain operations
Change tracking
Relationships

Use Dapper for:

Reports
Complex queries
Read-heavy APIs
Stored procedures
Performance-sensitive queries

44. Hybrid Repository Example

public class EmployeeService
{
    private readonly EmployeeDbContext _context;
    private readonly IDbConnection _connection;

    public EmployeeService(
        EmployeeDbContext context,
        IDbConnection connection)
    {
        _context = context;
        _connection = connection;
    }
}

You can then use:

// EF Core
await _context.Employees.AddAsync(employee);
await _context.SaveChangesAsync();

and:

// Dapper
var result = await _connection.QueryAsync<EmployeeReport>(
    reportSql);

45. Advantages of Dapper

1. Lightweight

Dapper has a small abstraction layer.

2. High SQL Control

Developers write the SQL directly.

3. Excellent for Complex Queries

SQL features such as:

CTE
JOIN
Window Functions
Stored Procedures
Temporary Tables
Aggregation
Database-specific features

can be used naturally.

4. Good Performance

Dapper avoids many ORM features that introduce additional processing.

5. Easy to Integrate

It works directly with ADO.NET connections and transactions.


46. Disadvantages of Dapper

1. More SQL Code

Developers must write SQL manually.

2. No Change Tracking

You must explicitly update the database.

3. No Built-in Migrations

A separate migration solution is required.

4. Relationship Handling

Complex relationships require additional SQL and mapping.

5. Maintenance

Large applications can end up with many SQL strings.

For example:

Repository
   |
   +-- SQL Query 1
   +-- SQL Query 2
   +-- SQL Query 3
   +-- SQL Query 4
   +-- SQL Query 5
   ...

Maintaining these queries requires discipline.


47. Advantages of EF Core

1. Productivity

CRUD operations require relatively little code.

2. LINQ

You can query using strongly typed C# expressions.

var employees = await context.Employees
    .Where(x => x.Salary > 50000)
    .OrderBy(x => x.Name)
    .ToListAsync();

3. Change Tracking

EF Core automatically tracks entity changes.

4. Relationships

Relationships are modeled naturally.

5. Migrations

Database schema changes can be managed through migrations.

6. Strong Typing

Many errors can be caught at compile time.

7. Integration with .NET

EF Core integrates naturally with:

ASP.NET Core
Dependency Injection
LINQ
Async/Await
Configuration
Logging
Testing

48. Disadvantages of EF Core

1. Abstraction Overhead

EF Core performs more work than a lightweight data-access library.

2. Generated SQL

Developers may not have direct control over every aspect of generated SQL.

3. Learning Curve

You need to understand:

DbContext
Change Tracking
LINQ
Relationships
Loading strategies
Migrations
Transactions
Query translation

4. N+1 Query Problems

Poorly designed loading can result in many database queries.

5. Complex SQL

Some highly database-specific SQL can be more straightforward to express directly using SQL/Dapper.


49. What is N+1 Query Problem?

Suppose we load departments:

var departments =
    await context.Departments.ToListAsync();

Then separately query employees for each department.

If there are 100 departments:

1 query
+
100 queries
=
101 queries

This is the N+1 problem.

It can cause serious performance issues.

Possible solutions include:

Include()

or projection:

.Select(...)

or using an optimized SQL query/Dapper.


50. EF Core Projection

Instead of loading the entire entity:

var employees = await context.Employees
    .Select(x => new EmployeeDto
    {
        Id = x.Id,
        Name = x.Name
    })
    .ToListAsync();

This can generate SQL that selects only the required columns.


51. Security Comparison

Both Dapper and EF Core can be secure.

The developer must follow secure coding practices.

Important practices:

Parameterized queries
Least-privilege database accounts
Secrets management
Azure Key Vault
Managed Identity
Input validation
Authorization
HTTPS
Auditing

Never put passwords directly into source code.

Bad:

Server=myserver;
User Id=admin;
Password=MyPassword123;

In Azure environments, consider:

Managed Identity
        |
        v
Azure SQL

and/or secure secret management where credentials are required.


52. Azure SQL with EF Core

A typical Azure architecture:

Internet
   |
Azure Front Door / Application Gateway
   |
API Management
   |
ASP.NET Core API
   |
EF Core
   |
Azure SQL Database

53. Azure SQL with Dapper

Dapper fits the same architecture:

Internet
   |
API Management
   |
ASP.NET Core API
   |
Dapper
   |
Azure SQL Database

The difference is primarily how the application accesses the database.


54. Testing EF Core

EF Core repositories/services can be tested using approaches such as:

Real SQL Server
SQL Server test container
SQLite where appropriate
Mocked abstractions in specific cases

For realistic database behavior, integration tests against a real SQL Server-compatible database are often more representative than relying exclusively on mocks.


55. Testing Dapper

Dapper-based repositories are also commonly tested using:

SQL Server test database
Testcontainers
Docker
Integration tests

Example architecture:

Integration Test
       |
       v
Dapper Repository
       |
       v
SQL Server Container

This provides realistic SQL execution.


56. Dependency Injection

EF Core:

builder.Services.AddDbContext<EmployeeDbContext>(
    options =>
        options.UseSqlServer(connectionString));

Dapper:

builder.Services.AddScoped<IDbConnection>(
    _ => new SqlConnection(connectionString));

In modern applications, it is also common to create a connection factory abstraction rather than injecting a raw connection everywhere.


57. Which One Should You Choose?

There is no universal answer.

Consider the application's requirements.

Choose EF Core when:

CRUD-heavy application
Domain-driven design
Complex entity relationships
Change tracking required
Rapid application development
Code-first migrations
LINQ-heavy application
Strong domain model

Choose Dapper when:

SQL-heavy application
Complex reporting
Existing stored procedures
Fine SQL control required
Read-heavy APIs
Database-specific SQL
Very lightweight data-access layer desired

Choose both when:

Business/domain operations -> EF Core

Complex queries/reports -> Dapper

58. Interview Question: Is Dapper faster than EF Core?

A good interview answer:

Dapper generally has less abstraction and less ORM overhead, so it can perform very well for SQL-centric operations. However, it is not correct to say that Dapper is always faster. Actual performance depends on query design, indexing, database workload, network latency, result size, tracking, and application architecture. Properly optimized EF Core queries can also provide excellent performance.


59. Interview Question: Does Dapper track changes?

No.

Dapper does not provide EF Core-style change tracking.

The developer explicitly executes INSERT, UPDATE, or DELETE statements.


60. Interview Question: Does EF Core always generate efficient SQL?

No.

EF Core generates SQL based on the LINQ expression and model configuration, but developers still need to understand the SQL being generated.

For performance-critical queries, inspect:

Generated SQL
Execution Plan
Indexes
Query duration
Database waits
Logical reads

61. Interview Question: Can Dapper call stored procedures?

Yes.

Example:

await connection.QueryAsync<Employee>(
    "GetEmployees",
    parameters,
    commandType: CommandType.StoredProcedure);

62. Interview Question: Can EF Core use stored procedures?

Yes.

EF Core supports raw SQL and stored procedure-related database operations.

However, the exact API depends on whether you are querying entities, executing commands, or using EF Core's newer modification stored-procedure capabilities.


63. Interview Question: Can Dapper perform transactions?

Yes.

Dapper uses ADO.NET transaction support.

using var transaction =
    connection.BeginTransaction();

64. Interview Question: Can EF Core and Dapper use the Same Database?

Yes.

For example:

                     SQL Server
                         |
             +-----------+-----------+
             |                       |
          EF Core                 Dapper
             |                       |
       Write operations         Read operations

They can coexist in the same application.


65. Interview Question: Which is better for Microservices?

Neither is universally better.

The decision should depend on the microservice's responsibilities.

For example:

Order Service
    |
    +-- EF Core

because it contains domain relationships and transactional business operations.

A:

Reporting Service
    |
    +-- Dapper

may be appropriate when it is primarily SQL/reporting focused.

Different microservices can use different data-access technologies.


66. Recommended Enterprise Architecture

For a large ASP.NET Core application, a practical architecture can be:

                    Client
                      |
                      v
                API Management
                      |
                      v
                ASP.NET Core
                      |
              +-------+-------+
              |               |
          Commands          Queries
              |               |
              v               v
           EF Core          Dapper
              |               |
              +-------+-------+
                      |
                  SQL Server

The important principle is:

Select the data-access technology based on the use case rather than choosing a technology simply because it is popular.


67. Dapper vs EF Core – Final Comparison

AreaDapperEF Core
AbstractionLowHigh
SQL ControlExcellentGood
CRUD ProductivityGoodExcellent
Change TrackingNoYes
LINQLimitedExcellent
RelationshipsManualExcellent
MigrationsExternalBuilt-in
Stored ProceduresExcellentSupported
Complex SQLExcellentGood
PerformanceVery goodVery good
LearningEasier initiallyMore concepts
Domain ModelingManualStrong
Read ModelsExcellentExcellent
Write ModelsGoodExcellent
ReportingExcellentGood/Excellent depending on query
Large Enterprise ApplicationVery goodVery good
Hybrid UsageYesYes

68. Real-World Recommendation

For a typical enterprise .NET application, don't think:

Dapper OR EF Core

Think:

Where does each technology provide the most value?

For example:

                   ASP.NET Core
                         |
                 Application Layer
                         |
             +-----------+-----------+
             |                       |
        Business Commands          Queries
             |                       |
             v                       v
          EF Core                 Dapper
             |                       |
             +-----------+-----------+
                         |
                     SQL Server

EF Core can handle:

Aggregate updates
CRUD
Transactions
Relationships
Change tracking
Domain operations

Dapper can handle:

Reports
Dashboards
Complex joins
Read models
Stored procedures
SQL-specific operations
Performance-sensitive queries

69. Final Conclusion

Both Dapper and Entity Framework Core are excellent database-access technologies for .NET, but they have different philosophies.

Dapper

Think:

"I want control over my SQL and a lightweight mapping layer."

EF Core

Think:

"I want an ORM that manages entities, relationships, tracking, LINQ and database schema evolution."

For many enterprise applications, the best architecture is not necessarily choosing one exclusively.

A hybrid approach can be very effective:

             ASP.NET Core Application
                       |
          +------------+------------+
          |                         |
       EF Core                    Dapper
          |                         |
    Business/Data               Reporting/
    modifications               Read models
          |                         |
          +------------+------------+
                       |
                    SQL Server

The most important skill for a senior .NET developer is not simply knowing Dapper vs EF Core, but understanding:

  • How SQL is executed

  • How connections are managed

  • How transactions work

  • How indexes affect queries

  • How to avoid N+1 queries

  • How to optimize EF Core queries

  • How to write efficient Dapper SQL

  • How to analyze execution plans

  • How to handle concurrency

  • How to design repositories and services

  • How to secure database access

  • How to monitor production database performance

Ultimately, database design, SQL quality, indexing, query patterns, and architecture usually have a much larger impact on application performance than simply selecting Dapper or EF Core.


Quick Interview Summary

If an interviewer asks:

"Dapper or EF Core — which one would you choose?"

A strong answer is:

"I would choose based on the application's requirements. EF Core is useful when we need an ORM with LINQ, change tracking, relationships, migrations and strong domain modeling. Dapper is useful when we need fine-grained SQL control, lightweight data access, complex reporting queries or existing stored procedures. In an enterprise application, I can also use both — EF Core for transactional/domain operations and Dapper for optimized read models and reporting. I would validate the decision using actual query performance, execution plans and application requirements rather than assuming one technology is always faster."

This is structured to work as a technical blog article and also as an interview-preparation reference. If you want, I can next turn this into a Dapper vs EF Core Part-2 with a complete ASP.NET Core Web API project, SQL Server database, Repository + Unit of Work + CQRS, and production-ready code.

Don't Copy

Protected by Copyscape Online Plagiarism Checker