09 Entity Framework
09 Entity Framework
NET MVC
Lesson 9: Entity Framework
Agenda
• What is Entity Framework
• Relation Types and Navigational Properties
• Database-First
• Model-First
• Code-First
• Migrations
What is Entity Framework
• Entity Framework (EF) is an open source object-relational
mapping(ORM) framework for ADO.NET.
• ADO.NET is a Data access technology built on .NET
• It enables .NET developers to work with a database through C#
objects, and eliminates the need for data access layers.
What is Entity Framework
What is an ORM?
• ORM tools take care of converting data between incompatible
systems. (ie, a database and our C# code)
• The create “virtual object databases” representing the data that can
be queried.
• Ie, DBSet<MyObject>, can be thought of as a virtual object database
• ORM tools will translate our code and objects to direct SQL executed
against the database
What is Entity Framework
Features of Entity Framework
• Modelling: Entity Framework creates an Entity Data Model based on the
objects with properties (get/set functions).
• Querying: EF will use the database provider to change LINQ queries into
the database native query language (like SQL for relational databases). It
can also allow us to execute raw SQL
• Change Tracking: EF will monitor the change state of our entities and
their respective properties.
• Saving: EF will execute all pending INSERT, UPDATE, and DELETE
commands to the database (tracked changes) with a SaveChanges()
command (or SaveChangesAsync() for asynchronous)
What is Entity Framework
Features of Entity Framework
• Concurrency: EF uses Optimistic Concurrency by default to protect
overwriting changes made by other users since the data was initially
queried
• Optimistic Concurrency is a fancy way of saying “Don’t put locks on data, but
check for pending changes before we commit”
• Caching: EF will cache data by default, so repeated querying will return
data from cache, instead of going back to the database
• Migrations: A set of powershell commands that can be operated from
the Package Manager Console to create or manage the database
schema
Relation Types and Navigational
Properties
Relation Types
• Data can be related in a wide array of ways, but they generally fall into
three types.
• One-to-One
• Every Person can only have one Drivers License issues them (barring other
countries/states/provinces/etc.)
• One-to-Many
• A Band can record many Albums
• Many-to-Many
• Students can enroll in a multitude of Courses, and each Course can have many
Students enrolled in it
Relation Types and Navigational
Properties
Navigational Properties
• An optional property on Entity types that allow for navigation
between associations
• These properties themselves don’t hold any significant data, they
just allow us to reach the other side of the relationship
Relation Types and Navigational
Properties
Navigational Properties – one-to-one
• Navigational property is just a property of the type we are linking to
• The entity Person generated from the below Model will have a
property License of type ‘License’, and vice versa for the License entity.
Relation Types and Navigational
Properties
Navigational Properties – one-to-many
• One half of the association will have a Collection<TEntity>, referencing
the entity on the other end of the association (the ‘many’)
• The other half will have a single Entity property, referencing the ‘one’
of the relationship
Relation Types and Navigational
Properties
Navigational Properties – many-to-many
• Leverages an intermediary table to facilitate the relationship. Each half of the
relationship will have a Collection (representing ‘many’) of the intermediary
entity. And the Intermediary object will have a single Entity of both sides.
Developing With Entity Framework
• There are three main approaches for working with Entity
Framework;
• Database-first approach, where our database already exists, and we will
generate our models and entities off of it
• Model-first approach, where we design a data model and generate a
database and entities off of it
• Code-first approach, where we simply write code, and generate a database
off of the code we write, or map entities to existing database schemas
Developing With Entity Framework
Which approach to use?
https://docs.microsoft.com/en-us/ef/ef6/modeling/
Database-First Approach
Creating a SQL Database in Visual Studio
• First we need to have a database created so we can generate our
Model from it
• Visual Studio can make a SQL Database for us, by creating a new
“SQL Server Database Project”
Database-First Approach
Creating a SQL Database in Visual Studio
• First, right-click on the project name,
add, Table..
• This will add a new table.sql file to
our project
Database-First Approach
Creating a SQL Database in Visual Studio
• Once we have our table created, we can modify it by writing raw T-
SQL, or by left-clicking on the row below the last row to add a new
column
Database-First Approach
Creating a SQL Database in Visual Studio
• Once we have our table created, we can modify it by writing raw T-
SQL, or by left-clicking on the row below the last row to add a new
column
• CREATE TABLE [SCHEMA].[TABLENAME]
([ColName] [ColType] (NOT NULL) (PRIMARY KEY)
…
(CONSTRANT) (CONSTRAINT NAME) (FOREIGN KEY) (COLUMN
NAME) (REFERENCES) (SCHEMA).(TABLE)(COLUMN)
)
Database-First Approach
SQL Example
CREATE TABLE [dbo].[Enrollments]
(
[Id] INT NOT NULL PRIMARY KEY,
[CourseId] INT NOT NULL,
[StudentId] INT NOT NULL,
CONSTRAINT [FK_dbo.Enrollment_dbo.Course_CourseId] FOREIGN KEY ([CourseID])
REFERENCES [dbo].[Course] ([Id]) ON DELETE CASCADE,
CONSTRAINT [FK_dbo.Enrollment_dbo.Student_StudentId] FOREIGN KEY ([StudentID])
REFERENCES [dbo].[Student] ([Id]) ON DELETE CASCADE
)
Database-First Approach
Creating a SQL Database in Visual Studio
• The database can be generated by ‘Running’ the solution.
• We are then able to see our database in the “SQL Server Object
Explorer” (View > SQL Server Object Explorer)
• The default localhost is (localdb)\ProjectModels
• Expand that server, in the Databases folder we should see our sample
database. We can then manually add data by expanding the database,
tables, and going into view data
Database-First Approach
Creating a Model and Context from the Database
• Within an MVC solution, we can add the connection to the database
and generate our model, context, and entities
• Right-click anywhere in our
MVC select, add new item,
and look for
“ADO.NET Entity Data Model”
Database-First Approach
Creating a Model and Context from the Database
Database-First Approach
Model-First Approach
Creating a Model in Visual Studio
• We can create a model within our MVC application by right clicking
the Project (or model directory) and creating a new “ADO.NET Entity
Data Model”
• This time in the Wizard, we will want to select “Empty EF Designer
Model”
Model-First Approach
Creating a Model in Visual Studio
Model-First Approach
Creating a Model in Visual Studio
Model-First Approach
Creating a Model in Visual Studio
Model-First Approach
Creating a Model in Visual Studio
Code-First Approach
Code First Approach to define our Model
• We can create an Entity for each Table, and create our “Context”
class that implements the DbContext class, and add a
DbSet<TEntity> properties for every table
• This is the approach we have been taking for the duration of the
course
• Once the project is built and executed, it will create the database for
us.
Code-First Approach
Code First Approach with an existing database
• Right-click project, add new Item, and we want to create a new
“ADO.NET Entity Data Model”
• This time, select Code First From Database
• Go through the steps to connect to the local database
• You will be prompted on which objects to import
Code-First Approach
Code First Approach – OnModelCreating
• Override function of DbContext
• Can be used to further customize our models
• modelBuilder.Entity<TEntity>() is the gateway to modifying the
mapping
• We can use this to further define properties, relationships, optional
properties, etc.
Code-First Approach
Code First Approach – Migrations
• If our Model changes, we can use Migrations to generate SQL scripts
that will alter our databases accordingly
• Open the Package Manager Console and execute the command
‘Enable-Migrations’.
• This will create a configuration.cs file that will specify seed data,
register providers, etc. We wont be changing anything in this file
• <timestamp>_InitialCreate.cs is the very first migration to create the
database
Code-First Approach
Code First Approach – Migrations
• At a high level, every time we make model changes, we can run the
‘Add-Migration <migration Name>’
• And once we are happy with our migration, we can apply it to the
database via the ‘Update-Database’ command
Demonstration
• Creating a Data Model from scratch and generating a database and
context
• Creating a Database first, and then creating an application to hook
into the database, and generate the context and models off of an
existing database
• Enabling Migrations and stepping through creating a migration script