0% found this document useful (0 votes)
17 views23 pages

Entity Framework

Entity Framework Core is an Object-Relational Mapper (ORM) that enables .NET developers to interact with various relational databases using .NET objects. It supports multiple mapping approaches, including Code First, Database First, and hand-coded models, and provides features like DbContext, DbSet, and Migrations for managing database interactions. Additionally, EF Core allows for configuring entity relationships and mappings through conventions, data annotations, and Fluent APIs.

Uploaded by

Reham Khaled
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views23 pages

Entity Framework

Entity Framework Core is an Object-Relational Mapper (ORM) that enables .NET developers to interact with various relational databases using .NET objects. It supports multiple mapping approaches, including Code First, Database First, and hand-coded models, and provides features like DbContext, DbSet, and Migrations for managing database interactions. Additionally, EF Core allows for configuring entity relationships and mappings through conventions, data annotations, and Fluent APIs.

Uploaded by

Reham Khaled
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Entity Framework Core

It's an Object-Relational Mapper (ORM) that allows developers to interact with relational
databases using .NET objects. EF Core supports a wide range of database providers such
as SQL Server, SQLite, PostgreSQL, MySQL, and more.

Database Models [Object]


[Relational]

Model development (Mapping) approaches :

Code First *Most Common Used*


● From Code (Models) Generate DB (Tables , Views)
● Generate a model from an existing database Database First (Reverse Engineering)

● Hand-code a model to match the database


Entity Framework Core
ORM : Object Relational Mapper

Database Models [Object]


[Relational]

Row

L2E (Linq To Entity : Query Object


Clas
Framework) Model s
Entity Framework Core
DbContext
: Central class in EF Core, it represents a session between your application and the database ,
tracks changes to entities and handles operations like querying and saving data

DbSet :
Represents a collection of entities of a specific type that can be queried or saved each Dbset
represents a table in the database .

Migrations
: They allow you to develop your database schema over time as your model changes.

Change Tracker :
EF Core automatically tracks changes to entities so You can detect what data needs to be
updated when you call SaveChanges()
Mapping Ways :
EF Core uses several techniques to handle this mapping, Each of these techniques
allows developers to configure the mapping between C# entities (classes) and
database tables (schemas)

1. By Convention

2. Data Annotation

3. Fluent API
Mapping Ways (By
Convention)
EF Core follows a set of default conventions to map classes to database tables,
and properties to columns, without requiring explicit configuration

Example 01
Migration :
To Add Migration : Add-Migration “Migration’s Name”

To Apply Migration : Update-Database


To Remove Last Migration : Remove-Migration (Must Be Not
Applied)
To Rollback Migration : Update-Database -Migration
PreviousMigration
To Rollback First Migration : Update-Database 0
To Rollback Then Remove Last Migration : Remove-Migration -
Force
Mapping Ways (Data Annotation)
They are attributes that you can apply to your POCO classes and their properties
to specify how EF Core should map them to the database.
Attributes Like the Following :
[Key [NotMapped]
Specifies that a property should not be mapped to a database
] Marks a property as the primary key for the entity column.
[Table(“TableName”
)] Specifies the name of the database table to which the entity is mapped
[MaxLength] and
[MinLength]
Used to specify the maximum and minimum length of string properties

[Column("ColName", TypeName = " ")]


Maps a property to a specific column in the database specifying column types, lengths, and other
properties
[Required]
Marks a property as required (the property as nullable for reference types and non-nullable for value types If this
annotation is not provided)
Mapping Ways (Fluent APIs)
Mapping Way used to configure entity properties, relationships, and mappings when
working with Code-First development. Gives you more control over the database
schema and relationships compared to Data Annotations.

● Fluent API configurations are defined inside the OnModelCreating method of your
DbContext or through separate configuration classes using the
IEntityTypeConfiguration<T> interface.
Mapping Ways (Fluent APIs- Configuration
classes)
Mapping Fluent API configurations through separate configuration

classes using the IEntityTypeConfiguration<T> interface. This improves

code organization and maintainability.


Entity Framework Core
ORM : Object Relational Mapper

Database Models [Object]


[Relational]

Row

L2E (Linq To Entity : Query Object


Clas
Framework) Model s
Query Object Model
Entry State :

Database ‫ ملوش عالقه بال‬object ‫ال‬


Detached
:Unchange
‫ بس ماحصلش عليه‬database ‫ موجود في ال‬object ‫ال‬

d: Deleted ‫ واتعمله‬database ‫ موجود في ال‬object ‫تغير ال‬


Deleted:
Modified:
Change ‫ وحصل عليه‬database ‫ موجود في ال‬object ‫ال‬

Added:
Add ‫ واتعمله‬Database ‫ مش موجود في ال‬object ‫ال‬
Relationships Between
Classes:
How To Map Relationship Among Tables
(Database)?
Employees Departments

Id Nam Age DepartmentI Id DeptNam


e d e
Class Employee Class Department
{ {
Public Long Id {get; set;}
Public int Id {get; set;}
Public string DeptName {get;
Public string Name {get;
set;}
set;}
}
int Age
Public Long {get; set;} {get;
DepartmentId
set;}
} Entity Framework Will Not Map
Relationship
Relationships Between
Classes:
How To Map Relationship Among Tables (Entity
Framework)?
EF Core supports different types of relationships between tables, which are represented using ( navigation
properties, foreign keys, and Fluent API configurations )

Employees Departments

Id Nam Age DepartmentI Id DeptNam


e d e
Class Employee Class Department
{ {
Public int Id {get; set;} Public Long Id {get; set;}
Public string Name {get; Public string DeptName {get;
set;} set;}
Public List<Employee> Employees
int Age
Public Long {get; set;} {get;
DepartmentId {get; set;}
set;}
Public Department Dept {get; set;} }
Navigational Property
Relationships Between
Classes:
Mapping OneToOne Relationship

A One-to-One (1:1) relationship means that each record in First

Table is associated with exactly one record in Second Table.


1 Manag
1
Employee e Department
An Employee manages a Department, and a Department must be managed by an
Employee

1. By Convention
2. Data Annotation
3. Fluent APIs
Mapping OneToOne
Relationship
By Convention :
● Foreign Key Must Named As :
○ <NameOfNavigationProperty>Id
○ <NameOfNavigationProperty><NameOfPrimaryKey>
○ <TypeOfNavigationProperty>Id
○ <TypeOfNavigationProperty><NameOfPrimaryKey>

● Foreign key property is Required Or Additional Configuration If you


Defined Both Navigation Property
● If You Didn't represent Foreign Key In Model Entity Framework will Create
Column In Table With Name
NameOfNavigationProperty><NameOfPrimaryKey>
Mapping OneToOne
Relationship
Data Annotation

● Use [ForeignKey] Attribute if needed (when FK name does not match the related
entity's PK)

Fluent APIs

● Use Fluent APIs When FK property name does not match PK , Need custom FK
constraints
Mapping OneToOne
Relationship
1 1
Employee Has Address
An Employee Has One Address And Each Address Must Assigned To One
Employee

EF Core does not automatically configure owned entities by convention You Must Use :
Data Annotation → [Owned]
Or Fluent API → .OwnsOne()
Mapping OneToOne
Relationship

Employe 1 1
Has Address
e [Self
An Employee Has One Address And Each Address May Assign To One
Employee Study]
One to One Relationship Both Side Optional
Relationships Between
Classes:
Mapping OneToMany Relationship

A One-to-Many (1:M) relationship means that each record in First

Table is associated with many record in Second Table.


M 1
Employee Works Department
An Employee Must Works in a Department, and a Department Must has many
Employees

1. By Convention
2. Data Annotation
3. Fluent APIs

You might also like