Entity Framework
Entity Framework
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.
Row
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”
● 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
Row
Added:
Add واتعملهDatabase مش موجود في الobject ال
Relationships Between
Classes:
How To Map Relationship Among Tables
(Database)?
Employees Departments
Employees Departments
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>
● 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
1. By Convention
2. Data Annotation
3. Fluent APIs