Ilovepdf Merged
Ilovepdf Merged
Entity Framework
The following figure illustrates where the Entity Framework fits into
your application.
As per the above figure, Entity Framework fits between the business
entities (domain classes) and the database. It saves data stored in
the properties of business entities and also retrieves data from the
database and converts it to business entities objects automatically.
Entity Framework Features
Cross-platform: EF Core is a cross-platform framework which can run
on Windows, Linux and Mac.
Modelling: EF (Entity Framework) creates an EDM (Entity Data Model)
based on POCO (Plain Old CLR Object) entities with get/set properties
of different data types. It uses this model when querying or saving
entity data to the underlying database.
Querying: EF allows us to use LINQ queries (C#/VB.NET) to retrieve
data from the underlying database. The database provider will
translate this LINQ queries to the database-specific query language
(e.g. SQL for a relational database). EF also allows us to execute raw
SQL queries directly to the database.
Change Tracking: EF keeps track of changes occurred to instances of
your entities (Property values) which need to be submitted to the
database.
Saving: EF executes INSERT, UPDATE, and DELETE commands to the
database based on the changes occurred to your entities when you call
the SaveChanges() method. EF also provides the
asynchronous SaveChangesAsync() method.
Concurrency: EF uses Optimistic Concurrency by default to protect
overwriting changes made by another user since data was fetched
from the database.
Transactions: EF performs automatic transaction management while
querying or saving data. It also provides options to customize
transaction management.
Caching: EF includes first level of caching out of the box. So, repeated
querying will return data from the cache instead of hitting the
database.
Built-in Conventions: EF follows conventions over the configuration
programming pattern, and includes a set of default rules which
automatically configure the EF model.
Configurations: EF allows us to configure the EF model by using data
annotation attributes or Fluent API to override default conventions.
Migrations: EF provides a set of migration commands that can be
executed on the NuGet Package Manager Console or the Command
Line Interface to create or manage underlying database Schema.
Entity Framework API (EF6 & EF Core) includes the ability to map
domain (entity) classes to the database schema, translate & execute
LINQ queries to SQL, track changes occurred on entities during their
lifetime, and save changes to the database.
Querying
EF API translates LINQ-to-Entities queries to SQL queries for
relational databases using EDM and also converts results back to
entity objects.
Saving
EF API infers INSERT, UPDATE, and DELETE commands based on the
state of entities when the SaveChanges() method is called. The
ChangeTrack keeps track of the states of each entity as and when an
action is performed.
Basic Workflow in Entity Framework
Here you will learn about the basic CRUD workflow using Entity
Framework.
1. First of all, you need to define your model. Defining the model includes
defining your domain classes, context class derived from DbContext,
and configurations (if any). EF will perform CRUD operations based on
your model.
2. To insert data, add a domain object to a context and call
the SaveChanges() method. EF API will build an appropriate INSERT
command and execute it to the database.
3. To read data, execute the LINQ-to-Entities query in your preferred
language (C#/VB.NET). EF API will convert this query into SQL query
for the underlying relational database and execute it. The result will be
transformed into domain (entity) objects and displayed on the UI.
4. To edit or delete data, update or remove entity objects from a context
and call the SaveChanges() method. EF API will build the appropriate
UPDATE or DELETE command and execute it to the database.
Developers can also perform various data creating, reading, updating and
deleting (CRUD) operations in relational databases without using SQL.
This capability is particularly useful for developers who either don't know
SQL or don't want to waste time writing SQL code. With ORM, they don't
have to understand and write SQL or rely on SQL query builders to add an
abstraction layer to the SQL code.
12/16/24, 2:02 PM Entity Framework - Data Annotations
Key
Timestamp
ConcurrencyCheck
Required
MinLength
MaxLength
StringLength
Table
Column
Index
ForeignKey
NotMapped
InverseProperty
Key
Entity Framework relies on every entity having a key value that it uses for tracking
entities. One of the conventions that Code First depends on is how it implies which
property is the key in each of the Code First classes.
Convention is to look for a property named “Id” or one that combines the class
name and “Id”, such as “StudentId”.
https://www.tutorialspoint.com/entity_framework/entity_framework_data_annotations.htm 1/19
12/16/24, 2:02 PM Entity Framework - Data Annotations
Now let’s suppose Student class used the name StdntID instead of ID. When Code First
does not find a property that matches this convention, it will throw an exception because
of Entity Framework’s requirement that you must have a key property. You can use the
key annotation to specify which property is to be used as the EntityKey.
Let’s take a look at the following code of a Student class which contains StdntID, but it
doesn’t follow the default Code First convention. So to handle this, a Key attribute is
added which will make it a primary key.
[Key]
public int StdntID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
When you run your application and look into your database in SQL Server Explorer you
will see that the primary key is now StdntID in Students table.
https://www.tutorialspoint.com/entity_framework/entity_framework_data_annotations.htm 2/19
12/16/24, 2:02 PM Entity Framework - Data Annotations
Entity Framework also supports composite keys. Composite keys are also primary keys
that consist of more than one property. For example, you have a DrivingLicense class
whose primary key is a combination of LicenseNumber and IssuingCountry.
When you have composite keys, Entity Framework requires you to define an order of the
key properties. You can do this using the Column annotation to specify an order.
https://www.tutorialspoint.com/entity_framework/entity_framework_data_annotations.htm 3/19
12/16/24, 2:02 PM Entity Framework - Data Annotations
Timestamp
Code First will treat Timestamp properties the same as ConcurrencyCheck properties,
but it will also ensure that the database field that code first generates is non-nullable.
Let’s take a look at a simple example by adding the TimeStamp property to the Course
class −
https://www.tutorialspoint.com/entity_framework/entity_framework_data_annotations.htm 4/19
12/16/24, 2:02 PM Entity Framework - Data Annotations
As you can see in the above example, Timestamp attribute is applied to Byte[] property
of the Course class. So, Code First will create a timestamp column TStamp in the
Courses table.
Explore our latest online courses and learn new skills at your own pace. Enroll and
become a certified expert to boost your career.
ConcurrencyCheck
The ConcurrencyCheck annotation allows you to flag one or more properties to be used
for concurrency checking in the database when a user edits or deletes an entity. If
you've been working with the EF Designer, this aligns with setting a property's
ConcurrencyMode to Fixed.
In the above Course class, ConcurrencyCheck attribute is applied to the existing Title
property. Now, Code First will include Title column in update command to check for
optimistic concurrency as shown in the following code.
https://www.tutorialspoint.com/entity_framework/entity_framework_data_annotations.htm 5/19
12/16/24, 2:02 PM Entity Framework - Data Annotations
Required Annotation
The Required annotation tells EF that a particular property is required. Let’s take a look
at the following Student class in which Required id is added to the FirstMidName
property. Required attribute will force EF to ensure that the property has data in it.
[Key]
public int StdntID { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
https://www.tutorialspoint.com/entity_framework/entity_framework_data_annotations.htm 6/19
12/16/24, 2:02 PM Entity Framework - Data Annotations
MaxLength
The MaxLength attribute allows you to specify additional property validations. It can be
applied to a string or array type property of a domain class. EF Code First will set the
size of a column as specified in MaxLength attribute.
Let’s take a look at the following Course class in which MaxLength(24) attribute is
applied to Title property.
When you run the above application, Code First will create a nvarchar(24) column Title
in the CourseId table as shown in the following image.
When the user sets the Title which contains more than 24 characters, then EF will throw
EntityValidationError.
https://www.tutorialspoint.com/entity_framework/entity_framework_data_annotations.htm 7/19
12/16/24, 2:02 PM Entity Framework - Data Annotations
MinLength
The MinLength attribute also allows you to specify additional property validations, just as
you did with MaxLength. MinLength attribute can also be used with MaxLength attribute
as shown in the following code.
EF will throw EntityValidationError, if you set a value of Title property less than the
specified length in MinLength attribute or greater than specified length in MaxLength
attribute.
StringLength
StringLength also allows you to specify additional property validations like MaxLength.
The only difference is that StringLength attribute can only be applied to a string type
property of Domain classes.
Entity Framework also validates the value of a property for StringLength attribute. If the
user sets the Title which contains more than 24 characters, then EF will throw
EntityValidationError.
Table
https://www.tutorialspoint.com/entity_framework/entity_framework_data_annotations.htm 8/19
12/16/24, 2:02 PM Entity Framework - Data Annotations
Default Code First convention creates a table name similar to the class name. If you are
letting Code First create the database, and also want to change the name of the tables it
is creating. Then −
You can use Code First with an existing database. But it's not always the case
that the names of the classes match the names of the tables in your database.
EF Code First will create a table with a specified name in Table attribute for a
given domain class.
Let’s take a look at the following example in which the class is named Student and by
convention, Code First presumes this will map to a table named Students. If that's not
the case, you can specify the name of the table with the Table attribute as shown in the
following code.
[Table("StudentsInfo")]
public class Student {
[Key]
public int StdntID { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
Now you can see that Table attribute specifies the table as StudentsInfo. When the table
is generated, you will see the table name StudentsInfo as shown in the following image.
https://www.tutorialspoint.com/entity_framework/entity_framework_data_annotations.htm 9/19
12/16/24, 2:02 PM Entity Framework - Data Annotations
You cannot only specify the table name but you can also specify a schema for the table
using Table attribute as shown in the following code.
[Key]
public int StdntID { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
You can see in the above example, the table is specified with admin schema. Now Code
First will create StudentsInfo table in Admin schema as shown in the following image.
https://www.tutorialspoint.com/entity_framework/entity_framework_data_annotations.htm 10/19
12/16/24, 2:02 PM Entity Framework - Data Annotations
Column
It is also the same as Table attribute, but Table attribute overrides the table behavior
while Column attribute overrides the column behavior. Default Code First convention
creates a column name similar to the property name. If you are letting Code First create
the database, and also want to change the name of the columns in your tables. Then −
EF Code First will create a column with a specified name in the Column attribute
for a given property.
Let’s take a look at the following example in which the property is named FirstMidName
and by convention, Code First presumes this will map to a column named FirstMidName.
If that's not the case you can specify the name of the column with the Column attribute
as shown in the following code.
https://www.tutorialspoint.com/entity_framework/entity_framework_data_annotations.htm 11/19
12/16/24, 2:02 PM Entity Framework - Data Annotations
You can see that Column attribute specifies the column as FirstName. When the table is
generated, you will see the column name FirstName as shown in the following image.
Index
The Index attribute was introduced in Entity Framework 6.1. If you are using an earlier
version, the information in this section does not apply.
You can create an index on one or more columns using the IndexAttribute.
Adding the attribute to one or more properties will cause EF to create the
corresponding index in the database when it creates the database.
Indexes make the retrieval of data faster and efficient, in most cases. However,
overloading a table or view with indexes could unpleasantly affect the
performance of other operations such as inserts or updates.
Indexing is the new feature in Entity Framework where you can improve the
performance of your Code First application by reducing the time required to
query data from the database.
https://www.tutorialspoint.com/entity_framework/entity_framework_data_annotations.htm 12/19
12/16/24, 2:02 PM Entity Framework - Data Annotations
You can add indexes to your database using the Index attribute, and override the
default Unique and Clustered settings to get the index best suited to your
scenario.
Let’s take a look at the following code in which Index attribute is added in Course class
for Credits.
You can see that the Index attribute is applied to the Credits property. When the table is
generated, you will see IX_Credits in Indexes.
By default, indexes are non-unique, but you can use the IsUnique named parameter to
specify that an index should be unique. The following example introduces a unique index
as shown in the following code.
https://www.tutorialspoint.com/entity_framework/entity_framework_data_annotations.htm 13/19
12/16/24, 2:02 PM Entity Framework - Data Annotations
ForeignKey
Code First convention will take care of the most common relationships in your model,
but there are some cases where it needs help. For example, by changing the name of
the key property in the Student class created a problem with its relationship to
Enrollment class.
While generating the database, Code First sees the StudentID property in the Enrollment
class and recognizes it, by the convention that it matches a class name plus “ID”, as a
foreign key to the Student class. However, there is no StudentID property in the Student
class, but it is StdntID property is Student class.
https://www.tutorialspoint.com/entity_framework/entity_framework_data_annotations.htm 14/19
12/16/24, 2:02 PM Entity Framework - Data Annotations
The solution for this is to create a navigation property in the Enrollment and use the
ForeignKey DataAnnotation to help Code First understand how to build the relationship
between the two classes as shown in the following code.
You can see now that the ForeignKey attribute is applied to the navigation property.
NotMapped
By default conventions of Code First, every property that is of a supported data type and
which includes getters and setters are represented in the database. But this isn’t always
https://www.tutorialspoint.com/entity_framework/entity_framework_data_annotations.htm 15/19
12/16/24, 2:02 PM Entity Framework - Data Annotations
the case in your applications. NotMapped attribute overrides this default convention. For
example, you might have a property in the Student class such as FatherName, but it
does not need to be stored. You can apply NotMapped attribute to a FatherName
property which you do not want to create a column of in the database as shown in the
following code.
You can see that NotMapped attribute is applied to the FatherName property. When the
table is generated you will see that FatherName column will not be created in a
database, but it is present in Student class.
Code First will not create a column for a property, which does not have either getters or
setters as shown in the following example of Address and Age properties of Student
class.
https://www.tutorialspoint.com/entity_framework/entity_framework_data_annotations.htm 16/19
12/16/24, 2:02 PM Entity Framework - Data Annotations
InverseProperty
InverseProperty is used when you have multiple relationships between classes. In the
Enrollment class, you may want to keep track of who enrolled a Current Course and
Previous Course. Let’s add two navigation properties for the Enrollment class.
Similarly, you’ll also need to add in the Course class referenced by these properties. The
Course class has navigation properties back to the Enrollment class, which contains all
the current and previous enrollments.
Code First creates {Class Name}_{Primary Key} foreign key column, if the foreign key
property is not included in a particular class as shown in the above classes. When the
database is generated, you will see the following foreign keys.
https://www.tutorialspoint.com/entity_framework/entity_framework_data_annotations.htm 17/19
12/16/24, 2:02 PM Entity Framework - Data Annotations
As you can see that Code first is not able to match up the properties in the two classes
on its own. The database table for Enrollments should have one foreign key for the
CurrCourse and one for the PrevCourse, but Code First will create four foreign key
properties, i.e.
CurrCourse _CourseID
PrevCourse _CourseID
Course_CourseID, and
Course_CourseID1
To fix these problems, you can use the InverseProperty annotation to specify the
alignment of the properties.
https://www.tutorialspoint.com/entity_framework/entity_framework_data_annotations.htm 18/19
12/16/24, 2:02 PM Entity Framework - Data Annotations
As you can see the InverseProperty attribute is applied in the above Course class by
specifying which reference property of Enrollment class it belongs to. Now, Code First
will generate a database and create only two foreign key columns in Enrollments table as
shown in the following image.
We recommend that you execute the above example in a step-by-step manner for better
understanding.
https://www.tutorialspoint.com/entity_framework/entity_framework_data_annotations.htm 19/19
12/16/24, 2:00 PM Entity Framework - Code First Approach
Code First
Database First
Model First
In this chapter, we will briefly describe the code first approach. Some developers prefer
to work with the Designer in Code while others would rather just work with their code.
For those developers, Entity Framework has a modeling workflow referred to as Code
First.
Code First modeling workflow targets a database that doesn’t exist and Code
First will create it.
It can also be used if you have an empty database and then Code First will add
new tables to it.
Code First allows you to define your model using C# or VB.Net classes.
Additional configuration can optionally be performed using attributes on your
classes and properties or by using a fluent API.
https://www.tutorialspoint.com/entity_framework/entity_framework_code_first_approach.htm 1/6
12/16/24, 2:00 PM Entity Framework - Code First Approach
Code First is really made up of a set of puzzle pieces. First are your domain
classes.
The domain classes have nothing to do with Entity Framework. They're just the
items of your business domain.
Entity Framework, then, has a context that manages the interaction between
those classes and your database.
The context is not specific to Code First. It's an Entity Framework feature.
Code First adds a model builder that inspects your classes that the context is
managing, and then uses a set of rules or conventions to determine how those
classes and the relationships describe a model, and how that model should map
to your database.
All of this happens at runtime. You'll never see this model, it's just in memory.
Code First also has the ability to use that model to create a database if you
wanted to.
https://www.tutorialspoint.com/entity_framework/entity_framework_code_first_approach.htm 2/6
12/16/24, 2:00 PM Entity Framework - Code First Approach
It can also update the database if the model changes, using a feature called Code
First Migrations.
Environment Setup
To start working with EF Code First approach you need the following tools to be installed
on your system.
Explore our latest online courses and learn new skills at your own pace. Enroll and
become a certified expert to boost your career.
Step 2 − Select Windows from the left pane and Console Application from the template
pane.
https://www.tutorialspoint.com/entity_framework/entity_framework_code_first_approach.htm 3/6
12/16/24, 2:00 PM Entity Framework - Code First Approach
Step 4 − Right-click on your project in the solution explorer and select Manage NuGet
Packages…
This will open NuGet Package Manager, and search for EntityFramework. This will search
for all the packages related to Entity Framework.
Step 5 − Select EntityFramework and click on Install. Or from the Tools menu click
NuGet Package Manager and then click Package Manager Console. In the Package
Manager Console window, enter the following command: Install-Package
EntityFramework.
https://www.tutorialspoint.com/entity_framework/entity_framework_code_first_approach.htm 4/6
12/16/24, 2:00 PM Entity Framework - Code First Approach
When the installation is complete, you will see the following message in the output
window “Successfully installed 'EntityFramework 6.1.2' to EFCodeFirstDemo”.
https://www.tutorialspoint.com/entity_framework/entity_framework_code_first_approach.htm 5/6
12/16/24, 2:00 PM Entity Framework - Code First Approach
https://www.tutorialspoint.com/entity_framework/entity_framework_code_first_approach.htm 6/6
12/16/24, 1:59 PM Entity Framework - Database First Approach
The Database First Approach provides an alternative to the Code First and Model
First approaches to the Entity Data Model. It creates model codes (classes,
properties, DbContext etc.) from the database in the project and those classes
become the link between the database and controller.
The Database First Approach creates the entity framework from an existing
database. We use all other functionalities, such as the model/database sync and
the code generation, in the same way we used them in the Model First approach.
Let’s take a simple example. We already have a database which contains 3 tables as
shown in the following image.
Step 2 − To create the model, first right-click on your console project in solution
explorer and select Add → New Items…
https://www.tutorialspoint.com/entity_framework/entity_database_first_approach.htm 1/6
12/16/24, 1:59 PM Entity Framework - Database First Approach
Step 3 − Select ADO.NET Entity Data Model from middle pane and enter name
DatabaseFirstModel in the Name field.
Step 4 − Click Add button which will launch the Entity Data Model Wizard dialog.
https://www.tutorialspoint.com/entity_framework/entity_database_first_approach.htm 2/6
12/16/24, 1:59 PM Entity Framework - Database First Approach
https://www.tutorialspoint.com/entity_framework/entity_database_first_approach.htm 3/6
12/16/24, 1:59 PM Entity Framework - Database First Approach
Step 8 − Select all the tables Views and stored procedure you want to include and click
Finish.
You will see that Entity model and POCO classes are generated from the database.
Let us now retrieve all the students from the database by writing the following code in
program.cs file.
https://www.tutorialspoint.com/entity_framework/entity_database_first_approach.htm 4/6
12/16/24, 1:59 PM Entity Framework - Database First Approach
using System;
using System.Linq;
namespace DatabaseFirstDemo {
class Program {
When the above program is executed, you will receive the following output −
https://www.tutorialspoint.com/entity_framework/entity_database_first_approach.htm 5/6
12/16/24, 1:59 PM Entity Framework - Database First Approach
When the above program is executed, you will see all the students’ name which were
previously entered in the database.
We recommend you to execute the above example in a step-by-step manner for better
understanding.
https://www.tutorialspoint.com/entity_framework/entity_database_first_approach.htm 6/6