THE .NET FRAMEWORK
ENTITY FRAMEWORK
Mr. Jibran Rasheed Khan
What is .NET?
•.NET is a platform that provides a standardized set of services.
•A specific software framework
•Includes a common runtime
•Programming model for .NET
•Platform for running .NET managed code in a virtual machine
•Provides a very good environment to develop networked
applications and Web Services
•Provides programming API and unified language-independent
development framework
The .NetFramework
Architecture
•Common Language Specification (CLS)
areguidelines, that language should follow for
communicating with other .NET languages in a
seamless manner. (does mapping)
•Common Type System (CTS) is a base class
library that contains all type information
likeInt32, Int64, String , Booleanetc.
•Common Language Runtime (CLR)is the
execution engine for .NET applications and
serves as the interface between .NET
applications and the operating system.
The Core of .NetFramework
•Common Language Runtime
•Garbage collection
•Language integration
•Multiple versioning support
•Integrated security
•Framework Class Library
•Provides the core functionality:
ASP.NET, Web Services, ADO.NET, Windows Forms, IO, XML, etc
.NET Framework
Common Language Runtime
•Manages running code –like a virtual machine
•Threading
•Memory management
•No interpreter: JIT-compiler produces native code –during the program
installation or at run time
•Fine-grained evidence-based security
•Code access security
•Code can be verified to guarantee type safety
•No unsafe casts, no un-initialized variables and noout-
of-bounds array indexing
•Role-based security
.NET Framework
Common Language Runtime
.NET Framework
Managed Code
•Code that targets the CLR is referred to as managed code
•All managed code has the features of the CLR
•Object-oriented
•Type-safe
•Cross-language integration
•Cross language exception handling
•Multiple version support
•Managed code is represented in special Intermediate Language
(IL)
.NET Framework
Automatic Memory Management
•The CLR manages memory for managed code
•All allocations of objects and buffers made from a Managed Heap
•Unused objects and buffers are cleaned up automatically through
Garbage Collection
•Some of the worst bugs in software development are not
possible with managed code
•Leaked memory or objects
•References to freed or non-existent objects
•Reading of uninitialized variables
•Pointerlessenvironment
.NET Framework
Multiple Language Support
•.NET languages are compiled to an Intermediate Language (IL)
•IL is also known as MSIL or CIL
•CLR compiles IL in just-in-time (JIT) manner –each function is
compiled just before execution
•The JIT code stays in memory for subsequent calls
•Recompilations of assemblies are also possible
.NET Framework
Intermediate Language
•IL (MSIL or CIL) –Intermediate Language
•It is low-level (machine) language, like Assembler, but is Object-oriented
•CTS is a rich type system built into the CLR
•Implements various types (int, float, string, …)
•And operations on those types
•CLS is a set of specifications that all languages and libraries need
to follow
•This will ensure interoperability between languages
.NET Framework
Common Language Specification (CLS)
•All .NET languages have the same primitive data types. An intin
C# is the same as an intin VB.NET
•When communicating between modules written in any .NET
language, the types are guaranteed to be compatible on the
binary level
•Types can be:
•Value types –passed by value, stored in the stack
•Reference types –passed by reference, stored in the heap
•Strings are a primitive data type now
.NET Framework
Programming Languages
•Languages provided by Microsoft
•C++, C#, J#, VB.NET, JScript
•Third-parties languages
•Perl, Python, Pascal, APL, COBOL, Eiffel, Haskell, ML, Oberon, Scheme,
Smalltalk…
•Advanced multi-language features
•Cross-language inheritance and exceptions handling
•Object system is built in, not bolted on
•No additional rules or API to learn
.NET Framework
Programming Language: C#
•Mixture between C++, Java and Delphi
•Component-oriented
•Properties, Methods, Events
•Attributes, XML documentation
•All in one place, no header files, IDL, etc.
•Can be embedded in ASP+ pages
•Everything really is an object
•Primitive types aren’t magic
•Unified type system == Deep simplicity
•Improved extensibility and reusability
The .NET Framework
Common Language Runtime
•CLR manages code execution at runtime
•Memory management, thread management, etc.
Operating System
Common Language Runtime
.NET Framework
Base Class Library
•Object-oriented collection of reusable types
•Collections, I/O, Strings, etc.
Operating System
Common Language Runtime
.NET Framework (Base Class Library)
.NET Framework
Data Access Layer
•Access relational databases
•Disconnected data model
•Work with XML
Operating System
Common Language Runtime
.NET Framework (Base Class Library)
ADO .NET and XML
.NET Framework
ASP.NET & Windows Forms
•Access relational databases
•Disconnected data model
•Work with XML
Operating System
Common Language Runtime
.NET Framework (Base Class Library)
ADO .NET and XML
ASP .NET
Web Forms Web Services
Mobile Internet Toolkit
Windows
Forms
The .NET Framework
Common Language Specification
•Support wide range of
programming languages
•Use your favorite language
Operating System
Common Language Runtime
.NET Framework (Base Class Library)
ADO .NET and XML
ASP .NET
Web Forms Web Services
Mobile Internet Toolkit
Windows
Forms
C++ C#VB.NETPerlJ# …
The .NET Framework
C# and Visual Studio .Net
Operating System
Common Language Runtime
.NET Framework (Base Class Library)
ADO .NET and XML
ASP .NET
Web Forms Web Services
Mobile Internet Toolkit
Windows
Forms
Common Language Specification
C++ C# VB PerlJ# …
Visual Studio .NET
•Visual Studio .Net
is an Integrated
Development Environment
(IDE), a collection of
development tools exposed
through a common user
interface
The .NET Framework
Standards Compliance
Operating System
Common Language Runtime
.NET Framework (Base Class Library)
ADO .NET and XML
ASP .NET
Web Forms Web Services
Mobile Internet Toolkit
Windows
Forms
Common Language Specification
C++ C# VB PerlJ# …
Visual Studio .NET
Prog. Language
Submitted to ECMA
Web services –
XML, SOAP-based
XML-based
data access
Open Language
Specification
ENTITY FRAMEWORK
ENTITY FRAMEWORK
WHAT IS?
•Entity Framework was released in 2008, Microsoft's primary means of interacting between .NET
applications and relational databases
•It is a set of ADO.NET technologies that aid in developing data-driven software.
•It is an Object Relational Mapping (ORM)framework that allows an automated way to store and
access databases. The data access framework to bridge the gap between data structures and
objectsin the applications.
•It is available as part of the .NET development (version 3.5 SP1 and later)
•Microsoft’s latest and recommendedway for data access for .NET applications.
•It allows to developand maintaindata-oriented apps with less code than traditional applications
•It eliminatesthe majority of the data-access code that must routinely write.
•It won’t need to know about the underlying database tables and columns where data need to store
ENTITY FRAMEWORK
HIGH LEVEL VIEW
ENTITY FRAMEWORK
VERSION HISTORY
ADO.NET Entity
Framework Version
Supported
Framework & IDE
Features Detail
6.0
.NET Framework 4.5.1
and Visual Studio 2013
•AsyncQuery and Save
•Code-Based Configuration
•Dependency Resolution
•Interception/SQL logging
•Improved Connection Management
•Improved Transaction Support
5.0
.NET Framework 4.5 and
Visual Studio 2012
•EnumSupport in Code First and EF Designer
•Spatial Data Types in Code First and EF
Designer
•Table-Valued Functions
•Multiple Diagrams per Model
ENTITY FRAMEWORK
VERSION HISTORY
ADO.NET Entity
Framework Version
Supported
Framework & IDE
Features Detail
4.3
.NET Framework 4.0
and Visual Studio 2010
Code First Migrations
Automatic Migrations
4.2
.NET Framework 4.0
and Visual Studio 2010
The EF 4.2 release included the bug fixes to
EF 4.1
4.1
.NET Framework 4.0
and Visual Studio 2010
Code First development
Introduced DbContextAPI
Data Annotations and Fluent API Validation
ENTITY FRAMEWORK
VERSION HISTORY
ADO.NET Entity
Framework Version
Supported
Framework & IDE
Features Detail
4.0
.NET Framework 4.0
and Visual Studio 2010
Model-first development
POCO support
Lazy Loading
T4 Code Generation
3.5
.NET Framework 3.5
SP1 and Visual Studio
2008 SP1
This release provided basic O/RM support
using the Database first development
ENTITY FRAMEWORK
ARCHITECTURE
•EDM, Consists of Conceptual model, Mapping and Storage model.
•LINQ to Entities,Used to write queries against the object
model.
•Entity SQL,like L2E, but little more difficult.
•Object Service, Responsible for materialization.
•ECDP,Responsible to convert L2E or Entity SQL queries into a SQL
query.
•ADO.net, Communicates with the database using standard ADO
ENTITY FRAMEWORK
LAZY LOADING
Lazy Loadingis the strategy to identify resources as non-
blocking (non-critical) and load them only when needed.
It is the default behavior of Entity Framework, which means that the related
entitiesor child entities are loaded only when it is being accessed for the first
time. That means in simple words we can say that Lazy loading simply delays the
loading of related entities until you specifically request it.
ENTITY FRAMEWORK
ENTITY PROPERTY
Entities mainly consist of two types
1. Scalar Property
Scalar properties are those properties that are primitive. It maps a column in a database table that
stores the data. E.g., student id, student name, class are the scalar property of a student entity.
2. Navigation Property
This property is responsible for the relationship of one entity to another. There are two types of
navigation properties:
i) Reference Navigation Property
When an entity has the property of another type of entity property, it is called reference navigation
property. It points to a single entity but represents the multiplicity of one.
ii) Collective Navigation Property
When an entity has the property of generic collection type, it is known as collective navigation
property. It has the multiplicity of many.
ENTITY FRAMEWORK
ENTITY STATES
•The entity framework API maintains the state of each entity during its lifetime. Each entity has a
state based on the operation performed on it via the context class. The entity state represented by
an enumSystem.Data.Entity.EntityState.
•The entity framework API builds and executes the INSERT, UPDATE, and DELETEcommands based
on the state of an entity when the context.SaveChanges() method is called.
•The Context class not only holds the reference to all the entity objects as soon as retrieved from
the database, also keeps track of entity states.
•The change in entity state from the Unchangedto the Modifiedstate is the only state that's
automatically handled by the context.
•All other changes made explicitly by using methods of DbContextor DbSet.
•Entity States
•Added
•Modified
•Deleted
•Unchanged
•Detached
ENTITY FRAMEWORK
ENTITY STATES
ENTITY FRAMEWORK
APPROACHES
DATABASE FIRST
Model the database artifacts
(tables, views, primary keys,
foreign keys, etc.)
Allows you to use legacy database
in your ORM application
Low level control over the
database
Entity Data Model can be updated
whenever database schema
changes.
Database-first approach supports
stored procedure, view, etc.
MODEL FIRST
Creating a model using the Entity
Framework designer tools
Designer can generate DDL
statements to create the database
An easy-to-use UI allows quickly
create new entities
Separation of code and database in
a declarative format
Dropping and re-creating the
database is not a choice
This uses an .EDMX file to store
model and mapping information.
CODE FIRST
The primary focus is getting the
code and logic
Define entity model with classes
and mappings in code..
Entity Framework create (and
recreate) the database for you.
Does not use Entity Framework
visual design tool, neither to design
entities
There is no XML file –no EDMX file –
to represent model and storage
schemas
ENTITY FRAMEWORK
CHOOSING RIGHT WORK MODEL
ENTITY FRAMEWORK
WORKFLOW
ENTITY FRAMEWORK
FEATURES
•Multiple DB Support
Works with a variety both relational and non-relational
servers including Microsoft SQL, MySql, Oracle, and DB2.
•Cross-platform
a cross-platform framework which can run on Windows,
Linux and Mac
•Modelling
creates an EDM based on POCO (Plain Old CLR Object)
entities with get/set properties of different data types.
•Querying
use LINQ and SQL queries to retrieve data from the
underlying relational database.
•Change Tracking
keeps track of changes occurred to instances of entities
(Property values)
•Saving
executes INSERT, UPDATE, and DELETE commands when
call the SaveChanges()and SaveChangesAsync()method
•Concurrency
Optimistic Concurrency by default to protect
overwriting changes made by another user
•Transactions
performs automatic transaction management while
querying or saving data.
•Caching
repeated querying will return data from the cache
instead of hitting the database.
•Built-inConventions
follows conventions over the configuration which
automatically configure the EF model.
•Configurations
allows us to configure the EF model by using data
annotation attributes or Fluent API
•Migrations
commands can be executed on the NuGetPackage
Manager Console or CLI to create or manage underlying
database Schema.
ENTITY FRAMEWORK
ADVANTAGES
•Reduced development time
•Developers can work more application-centric
•Free from hard-coded dependencies on a particular data engine
•Mappings can be change without changing the application code
•L2Eprovides validation for writing queries against a conceptual model
•Integrates with all the .NET application programming models
•Worked well with ASP.NET, WPF, WCF, and WCF Data Services
DATABASE FIRST
PICTORIAL TOUR
HOW TOs
The steps involved in this example are as follows:
Create the new SQL Server database
Create the database objects
Create a new C# Class Library Project in Visual Studio 2012 Solution
Add a new ADO.NET Entity Data Model to project
Create a new Database Connection
Import the database objects into the EDM
Modify the EDM to accommodate the scalar-valued functions
01
02
03
04 05
06
07 08
09
12
11
10
Features
Advantages
MODEL FIRST
PICTORIAL TOUR
HOW TOs
The steps involved in this example are as follows:
Creating the model
Creating entities in the .edmx
Editing entity properties
Applying relationships to the entities
Name DatabaseSchema
Generating the database from the model
01 03
02
06
05
04
090807
10
11
12
1514
13
16 17 18
19 20 21
Features
Advantages
CODE FIRST
PICTORIAL TOUR
HOW TOs
The steps involved in this example are as follows:
Create a new Class Library
Create POCO (Plain Old CLR Object) classes
Add data annotations to the POCO classes.
Create enumclasses (if required)
Add Entity Framework to the Solution
Add a DbContextclass
Add ‘Code First Migrations’
Updates the database (if needed/made changes)
01 02
0304
04 05
06
07
FEATURES
ADVANTATES
Question & Answer
“A wise man can learn more from a foolish question than a fool can
learn from a wise answer.”
Bruce Lee