Sem 2 L4
Sem 2 L4
Application Development
Bishal Gharti Chhetri
[email protected]
Week-4
Agenda
• Database-Driven Application
• Traditional & Modern Approach
• ORM & EF Core
• Installing Necessary Dependencies
• Defining Models & Relationships
• Configuring DbContext
• Create & Apply Migration
| 2
Database-Driven Application
Database-Driven Application
• Applications that interact with a database to store, retrieve, and manage data.
• Typically follows a Three-Tier Architecture.:
• Data-Tier (Database - SQL/NoSQL)
• Business Logic Tier (Application Layer - logic & processing)
• Presentation Tier (User Interface - frontend interaction)
• Examples:
• Web Applications (e.g., E-commerce, CMS, Social Media)
• Desktop Applications (e.g., MS Access, Accounting Software)
• Mobile Applications (e.g., Banking Apps, Online Booking Apps)
| 4
Traditional Approach
• Raw SQL Queries:
• Direct interaction with the database using SQL statements.
• Developers write custom queries for CRUD (Create, Read, Update, Delete) operations.
• Manual Data Mapping:
• Developers map the results of SQL queries to application objects manually.
• Requires creating custom mapping logic between the database schema and application models.
• No Abstraction:
• No abstraction layer between the application and the database.
• Developers work directly with the database, making it harder to switch to different databases or scale the
application.
• Error-Prone and Maintenance Heavy:
• Manual SQL handling increases the chances of errors.
• Maintaining raw SQL and mapping code can become cumbersome, especially as the application grows.
| 5
Example > ADO.NET
| 6
ORM
Object-Relational Mapping/Mapper
Modern Approach
ORM
• Interact with a database without writing raw SQL queries.
• Maps database tables to classes, rows to objects, and columns to properties.
• Supports different database systems with minimal code changes.
• ORM Options:
• Entity Framework Core (EF Core)
• NHibernate
• Dapper
• micro-ORM focused on performance and simplicity.
| 8
EF Core
Entity Framework Core
EF Core
• Microsoft's official open-source, cross-platform Object-Relational Mapper (ORM) for .NET applications.
| 10
EF Core > Features
• Cross-Platform & Lightweight – Works on Windows, Linux, macOS with a modular design.
• Code-First Database Development Approach: Supports defining the database schema using C# classes and
migrations, without manually creating a database.
• LINQ Queries – Uses Language Integrated Query (LINQ) for querying any database supported by EF, which is then
translated into database-specific SQL.
• Change Tracking – Monitors entity modifications for efficient updates.
• Migrations – Manages & supports evolving database schema changes over time.
• Relationships & Configurations – Supports One-to-One, One-to-Many, and Many-to-Many mappings automatically
or manually via Fluent API or Data Annotations.
• Performance Optimizations – Includes batching, Raw SQL, compiled queries, and connection pooling.
• Transactions & Concurrency – Supports automatic and explicit transactions with optimistic concurrency.
• Database Providers – Works with SQL Server, SQLite, PostgreSQL, MySQL, and more.
• Integration with .NET – Works seamlessly with ASP.NET Core, Blazor, and other .NET applications.
| 11
Example > EF Core
| 12
Set-up
Install Dependencies
• Entity Framework Core (EF Core) : The base package for EF Core ORM.
• Microsoft.EntityFrameworkCore
• Database provider(s) : To Translate queries and commands into database-specific language and operations.
Microsoft.EntityFrameworkCore.SqlServer Microsoft.EntityFrameworkCore.Sqlite
Microsoft.EntityFrameworkCore.InMemory Microsoft.EntityFrameworkCore.Cosmos
MySql.EntityFrameworkCore Pomelo.EntityFrameworkCore.MySql
Npgsql.EntityFrameworkCore.PostgreSQL Oracle.EntityFrameworkCore
| 14
nuget.org
| 15
Install Dependencies > JetBrain Rider
| 16
Install Dependencies > Visual Studio
| 17
Model
Entitiy
Defining a Model
• Represent the structure of your database tables using C# classes.
• Typically referred to as entity or entity class.
• Each model contains properties that map to table columns.
| 19
Configuring a Model
• EF Core uses convention-based mapping, meaning it automatically configures your entity based on class properties.
• However, in many cases, you need custom configurations to:
• Specify table names, column types, or constraints
• Define relationships (One-to-One, One-to-Many, Many-to-Many)
• Configure indexes, default values, computed columns, etc.
• Approaches:
• Data Annotations (convenient)
• Fluent Api (comprehensive)
• Using OnModelCreating in DbContext
• Using Entity Type Configuration (IEntityTypeConfiguration<T>)
| 20
Configuring a Model > Data Annotations
• From System.ComponentModel.DataAnnotations
Attribute Purpose
[Key] Indicates the primary key of an entity.
[Required] Makes a property non-nullable (and thus enforces a NOT NULL column).
[MaxLength] Sets the maximum allowed length of string (or array) data; EF Core uses it to determine
column size.
[StringLength] Like MaxLength (and optionally sets a minimum length); it also influences the column’s size.
[ConcurrencyCheck] Includes the property in optimistic concurrency checks.
[Timestamp] Marks a property as a row-version/timestamp for concurrency control.
| 21
Configuring a Model > Data Annotations
• From System.ComponentModel.DataAnnotations.Schema
Attribute Purpose
[Table] Specifies the table (and optional schema) an entity is mapped to.
[ForeignKey] Marks a property as the foreign key for a navigation property.
[Column] Allows you to set the column name, database type, order, etc.
[NotMapped] Excludes a property or class from mapping to the database.
[DatabaseGenerated] Configures value generation (for example, Identity or Computed).
[InverseProperty] Identifies the corresponding navigation on the other end of a relationship.
[ComplexType] (New in EF Core 8) Marks a type as “complex” (owned) so that its properties are mapped as
part of the owning entity.
| 22
Microsoft.EntityFrameworkCore
| 23
Example
| 24
Example
| 25
Example
| 26
Example
Fluent Api using Entity Type Configuration
Or
| 27
Relationships
Relationships
• Define relationships using navigation properties and conventions or apply the Fluent API when necessary.
• Entity Relationship Diagram (ERD):
| 29
One-to-One (Required)
• Each book can have exactly one cover image, and each cover image belongs to exactly one book.
| 30
One-to-One (Optional)
• A Book doesn't necessarily need to have a cover image.
| 31
One-to-One (Strict)
• A cover image cannot exist without a Book, and each Book can have at most one cover image.
| 32
One-to-Many
• A series can include multiple books, and each book typically belongs to one series (or none), with a sequence
number indicating its order (e.g., "The Return of the King" of "The Lord of the Rings").
| 33
Many-to-Many
• A book can belong to multiple genres (e.g., "Fantasy" and "Adventure"), and a genre can include multiple books.
| 34
Many-to-Many (Explicit Bridge-Table)
| 35
Relationship > Fluent Api Configuration
| 36
DbContext
DbContext
• Acts as the bridge between the application and the database.
• Represents a database session, managing connection and tracking changes (Added, Modified, Deleted).
• Follows Repository pattern, exposing DbSet properties that function like repositories (providing query and CRUD
operations).
• DbSet<TEntity>: Represents collections of entities (e.g., DbSet<Book> Books, DbSet<Genre> Genres)
• Follows Unit of Work pattern, batching changes and coordinating the commit (or rollback) of a set of operations in
a single transaction.
| 38
DbContext
| 39
DbContext > Registration
| 40
appsettings.json
| 41
connectionstrings.com
| 42
Migration
Migration
• Set of instructions (or a "recipe") that tells the database how to modify its structure—such as creating tables,
adding columns, altering data types, or dropping elements—while preserving existing data where possible.
• EF Core migrations follow a code-first development approach.
• Keeps the database schema in sync with the application’s data model or code.
• Provides a version-controlled history of database changes.
• Basic Workflow
• Define Models & DbContext.
• Generate migration files using EF Core tools.
• Apply migrations to update the database schema.
| 44
Migration > Example
| 45
NuGet's PMC tool (Only VS)
> Microsoft.EntityFrameworkCore.Tools
| 46
NuGet's PMC tool (Only VS)
> Microsoft.EntityFrameworkCore.Tools
| 47
NuGet's PMC tool (Only VS)
> Microsoft.EntityFrameworkCore.Tools
| 48
.NET Core CLI
> dotnet-ef
| 49
.NET Core CLI
> dotnet-ef
| 50
.NET Core CLI
> dotnet-ef
| 51
Rider
> EF Core UI Plugin
| 52
Rider
> Entity Framework Core UI Plugin
| 53
| 54