0% found this document useful (0 votes)
5 views19 pages

Wad S03 - Orm

The document discusses Object Relational Mapping (ORM), explaining its definition, challenges such as impedance mismatch, and the differences between database-first and code-first approaches. It outlines the steps for implementing ORM in software development, including creating classes, building the database context, and generating migration scripts. Additionally, it lists commonly used ORM software products across various programming languages.

Uploaded by

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

Wad S03 - Orm

The document discusses Object Relational Mapping (ORM), explaining its definition, challenges such as impedance mismatch, and the differences between database-first and code-first approaches. It outlines the steps for implementing ORM in software development, including creating classes, building the database context, and generating migration scripts. Additionally, it lists commonly used ORM software products across various programming languages.

Uploaded by

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

‫المعهد العالي للعلوم التطبيقية والتكنولوجيا‬

‫تطوير تطبيقات الوب‬


‫الموضوع‪ :‬الربط العالقاتي لألغراض‬
‫‪Object Relational Mapping‬‬

‫المهندس محمود الياس‬

‫العام الدراسي‪2025 - 2024 :‬‬


‫السنة‪ :‬الرابعة – الفصل الثاني‬
‫االختصاص‪ :‬برمجيات‬
‫رقم الجلسة‪3 :‬‬
2 Headlines
➢ Definition
➢ Impedance Mismatch
➢ Code Generation
➢ Database-First vs Code-First
➢ Commonly Used ORM Software Products

Mahmoud ELIAS 28 February 2025


3 Handling Objects

var deptName = employee.Department.Name; Employee


Int EmployeeId
var empName = employee.Person.FirstName; Person Person
Department Department
var emps = employees
.Where(e => e.DepartmentId == 5) Person
.OrderBy(e => e.Id) Int PersonId
.Select(e => new String FirstName
{ String LastName
FName = e.Person.FirstName,
LName = e.Person.LastName Department
}); Int DepartmentId
String Name

Mahmoud ELIAS 28 February 2025


4 Definition
➢ ORM or Object Relational Mapping is a system that implements the responsibility of
mapping the Object to Relational Model
➢ That means it is responsible to store Object Model data into Relational Model and
further read the data from Relational Model into Object Model

Mahmoud ELIAS 28 February 2025


5 Impedance Mismatch (1)
➢ The Object Oriented model uses classes whereas the relational database uses tables,
this creates a gap (The Impedance Mismatch)

➢ Due to the difference between the two different models, getting the data and
associations from objects into relational table structure and vice versa requires a lot
of tedious programming

➢ Loading and storing objects using a tabular relational database exposes us to 5


mismatch problems:
➢ Granularity
➢ Inheritance
➢ Identity
➢ Associations
➢ Data navigation

Mahmoud ELIAS 28 February 2025


6 Impedance Mismatch (2)
➢ Granularity
➢ Granularity is the extent to which a system could be broken down into small parts
➢ Ex. Person details: we could break down person details into two classes; one is Person and
another is Address for code re-usability and code maintainability purpose
➢ But assume that to store Person details in database there is only one table called Person
➢ Sometimes you will have an object model which has more classes than the number of
corresponding tables in the database (we say that object model is more granular than the
relational model)
➢ Inheritance or Sub-types
➢ Inheritance is a natural concept in object-oriented programming languages
➢ RDBMSs do not define anything similar on the whole (except for some databases that do
have subtype support but it is completely non-standardized)
➢ Identity
➢ RDBMS defines exactly one notion of ‘sameness’: the primary key
➢ Most programming languages define both object identity a==b and object equality
a.equals(b)

Mahmoud ELIAS 28 February 2025


7 Impedance Mismatch (3)
➢ Associations
➢ Associations are represented as unidirectional references in Object Oriented languages
whereas RDBMSs associations are bidirectional by using foreign keys
➢ If you need bidirectional relationships in a programming language P.L., you must define the
association twice
➢ Data navigation
➢ The way you access data in P.L. is fundamentally different than the way you do it in a
relational database
➢ In P.L., you navigate from one association to another walking the object network
➢ This is not an efficient way of retrieving data from a relational database
➢ You typically want to minimize the number of SQL queries and thus load several entities via JOINs
and select the targeted entities before you start walking the object network

Mahmoud ELIAS 28 February 2025


8 Create Classes
public class Department public class Person
{ {
public int Id { get; set; } public int Id { get; set; }
public string Name { get; set; } public string FirstName { get; set; }
} public string LastName { get; set; }
public DateTime Birthdate { get; set; }
Person public bool Gender { get; set; }
Id }
FirstName
LastName
public class Employee
Birthdate Employee
Gender Id
{
HireDate public int Id { get; set; }
WorkNb public DateTime HireDate { get; set; }
DepartmentId public int WorkNb { get; set; }
Department
Id public int DepartmentId { get; set; }
Name }

Mahmoud ELIAS 28 February 2025


9 Classes with Navigation Properties

public class Employee


{
public int Id { get; set; }
public DateTime HireDate { get; set; }
public int WorkNb { get; set; }
public int DepartmentId { get; set; }

public Department Department { get; set; }


public Person Person { get; set; }
}

Mahmoud ELIAS 28 February 2025


10 Final form of Models
public partial class Employee
{
public int Id { get; set; }
public DateTime HireDate { get; set; }
public partial class Department public int WorkNb { get; set; }
{ public int? DepartmentId { get; set; }
public Department()
{ Employees = new HashSet<Employee>(); } public virtual Department? Department { get; set; }
public virtual Person IdNavigation { get; set; } = null!;
public int Id { get; set; } }
public string Name { get; set; } = null!;

public virtual ICollection<Employee> Employees { get; set; }


}

public partial class Person


{
public int Id { get; set; }
public string FirstName { get; set; } = null!;
public string LastName { get; set; } = null!;
public DateTime? Birthdate { get; set; }
public string? Gender { get; set; }

public virtual Employee? Employee { get; set; }


}
Mahmoud ELIAS 28 February 2025
11 DbContext
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Department>(entity =>
{
entity.ToTable("Department");
entity.Property(e => e.Name).HasMaxLength(250);
});

modelBuilder.Entity<Employee>(entity =>
{
entity.ToTable("Employee");
entity.Property(e => e.Id).ValueGeneratedNever();
entity.Property(e => e.HireDate).HasColumnType("date");
entity.HasOne(d => d.Department) modelBuilder.Entity<Person>(entity =>
.WithMany(p => p.Employees) {
.HasForeignKey(d => d.DepartmentId) entity.ToTable("Person");
.HasConstraintName("FK_Employee_Department"); entity.Property(e => e.Birthdate).HasColumnType("date");
entity.Property(e => e.FirstName).HasMaxLength(100);
entity.HasOne(d => d.IdNavigation) entity.Property(e => e.Gender)
.WithOne(p => p.Employee) .HasMaxLength(1)
.HasForeignKey<Employee>(d => d.Id) .IsUnicode(false)
.OnDelete(DeleteBehavior.ClientSetNull) .IsFixedLength();
.HasConstraintName("FK_Employee_Person"); entity.Property(e => e.LastName).HasMaxLength(100);
}); });

OnModelCreatingPartial(modelBuilder);

} Mahmoud ELIAS 28 February 2025


12 Code Generation
➢ Use templates to generate ORM, User Interfaces, and others

➢ Ex. CodeSmith Generator

Mahmoud ELIAS 28 February 2025


13 Database-First vs Code-First
➢ In the Code-First approach, we have full control over the code
and the database is just a store without any logic

➢ We don’t have to worry about creating and updating the


database
➢ We can just make the changes in our code and then sync everything easily with the
database

➢ The important thing to note is that the manual changes that we


make to the database could be lost during migration
➢ So, we should make changes to the code only

Mahmoud ELIAS 28 February 2025


14 Steps (1) – Install Packages and Build the Model
➢ Install needed packages:
➢ Microsoft.EntityFrameworkCore.SqlServer
➢ Microsoft.EntityFrameworkCore.Tools
➢ Microsoft.EntityFrameworkCore

➢ Build model classes:


public class Employee  Id is a primary key
{ It requires
[Key] using System.ComponentModel.DataAnnotations;
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Id { get; set; } => Id is auto-incremented
public string FirstName { get; set; }
identity
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public string PhoneNumber { get; set; }
public string Email { get; set; }
}

Mahmoud ELIAS 28 February 2025


15 Steps (2) – Build the Database Context
➢ Create the context file
public class CompanyContext : DbContext
{ using System.Data.Entity;
public CompanyContext(DbContextOptions options) : base(options)
{
}

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


}

Mahmoud ELIAS 28 February 2025


16 Steps (3) – Build the Database Context
➢ Define the connection string in the file appsettings.json:
{
"ConnectionStrings": {
"CompanyCS": "server=.; database=CompanyDB;Trusted_Connection=True;"
}
} server=myServerAddress;
Trusted Connection database=myDataBase;
user Id=myUsername;
password=myPassword;
➢ Add services to the ConfigureServices of Startup
Standard security
➢ Add the package Microsoft.AspNetCore.All
➢ Add the following DB service:

services.AddDbContext<CompanyContext>(options => Startup.ConfigureServices


options.UseSqlServer(Configuration.GetConnectionString("CompanyCS")));

Mahmoud ELIAS 28 February 2025


17 Steps (4) - Generate Migrations Script
➢ Run the following dotnet ef command from the Web project root to generate
migrations script:

dotnet ef migrations add InitialMigrations --project Or use the following statement from
..\Company.DataContext\Company.DataContext.csproj “Package Manager Console”:
--startup-project .\Company.Web.csproj add-migration InitialMigrations

public partial class InitialMigrations : Migration


{
protected override void Up (MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Employees",
columns: table => new
{
Id = table.Column<long>(nullable: false)
...
},
constraints: table => { table.PrimaryKey("PK_Employees", x => x.Id); });
}

protected override void Down (MigrationBuilder migrationBuilder)


{
migrationBuilder.DropTable(name: "Employees");
}
}
Mahmoud ELIAS 28 February 2025
20 Generate Classes from an Existing Database
➢ Run the following dotnet ef command from the Web project root to update
database from command prompt:
dotnet ef dbcontext scaffold "server=.\;database=CompanyDb;Trusted_Connection=True;
Encrypt=False;" Microsoft.EntityFrameworkCore.SqlServer -o Models

➢ This command creates a folder named “Models” containing a collection of class


files representing the entities in addition to a file for the DbContext class

➢ You can use the Package Manager Console statement (

Scaffold-DbContext "server=.\;database= CompanyDb;Trusted_Connection=True;


Encrypt=False;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

Mahmoud ELIAS 28 February 2025


21 Commonly Used ORM Software Products
➢ Hibernate for Java
➢ Entity Framework for .Net
➢ Doctrine and Eloquent (of Laravel) for PHP
➢ Django for Python
➢ ActiveRecord for Ruby

Mahmoud ELIAS 28 February 2025

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy