entity framework
TRANSCRIPT
Why Database Layer
Object Impedance Mismatch - RDBMS and OOP
Object Conversions - RDBMS to OOP and OOP to RDBMS
Needs Easy Conversion Process - Rise of ORM
ORM?
Many Frameworks - EF, NH, LINQ to SQL
RDBMS to NoSQL Support
Single RDBMS Support to Various RDBMS Support
DB Layer Uniformity Across the Organization
EF - Key Terms
Entity
Context - Object Context, Db Context
Deferred Execution
POCO - Plain Old CLR Object
LINQ to Entities, Entity SQL
Mapping, Conceptual Model, Storage Model
Projections
EF - Loading
Lazy, Eager Loading and Explicit Loading
Loading Navigation Properties
1. LazyLoadingEnabled = true
2. LazyLoadingEnabled = false & Include(“{Navigation Property}”)
3. LazyLoadingEnabled = false & {Navigation Property}.Load()
Modelling - Database First
Reverse engineer model in EF Designer
Classes auto-generated from model
Preferred approach for existing database
Modelling - Model First
Create model in EF Designer
Generate database from model
Classes auto-generated from model
Preferred approach for new database.
Modelling - Code First
Define classes and mapping in code
Database created from code
Migrations apply model changes to database
Preferred approach for new database. Generally
preferred in Agile/Scrum
Modelling - Fluent Api, Configuration and Conventions
Fluent Api - Chaining Api
Configuration with Fluent Api
Conventions
EF - Code First - Conventions
Convention: Table Name
Default: Entity + s (e.g Users)
Convention: Primary Key
Default: Id
Convention: Foreign Key Relation
Default: Entity + Id (e.g SubscriptionId)
EF - Code First - Data Annotations
Annotation: Table
=> Table(“{Name”})
Annotation: Key
=> Key
Annotation: ForeignKey
=> ForeignKey(“{Navigation Property”})
=> ForeignKey(“{Property”})
Homework
AddressBook - Design Db and Do CRUD operations on all entities
Executing Raw SQL - Plain, Stored Procedures
EF - Inheritance Strategy - TPH
Needs a column, discriminator, that will used to identify exact type.
Retrieving Type in TPH
Code First Configuration
Gives better performance but there are many duplicate data and nullable columns.
EF - Inheritance Strategy - TPT
Each entity maps to table. So CUD operations are faster
Code First Configuration
Retrieval is slower than TPH as it needs joins with base class/table.
EF - Inheritance Strategy - TPC
Each concrete entity maps to table.
Code First Configuration
Properties of abstract entity are combined with concrete entity and many data/columns duplications.
EDMX designer does not support this mapping. Manual modification is required.
EF - Concurrency - Optimistic
None: Default and there is no concurrency
Fixed: Original value of concurrency column is included in where part while generating SQL
Rows are not locked. Read operation can be never locked
EF - Concurrency - Pessimistic
Involves database locking operations. So it is slow
Use Transaction to achieve it
Read operation can be locked