0% found this document useful (0 votes)
18 views39 pages

Ilovepdf Merged

Entity Framework is an open-source ORM framework for .NET that allows developers to interact with data using domain-specific objects instead of database tables. It features cross-platform support, change tracking, LINQ querying, and automatic transaction management, among other capabilities. The document also discusses data annotations for configuring entity classes and the architecture of Entity Framework, including the Entity Data Model (EDM) and its components.

Uploaded by

Mohamad Iliyas
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)
18 views39 pages

Ilovepdf Merged

Entity Framework is an open-source ORM framework for .NET that allows developers to interact with data using domain-specific objects instead of database tables. It features cross-platform support, change tracking, LINQ querying, and automatic transaction management, among other capabilities. The document also discusses data annotations for configuring entity classes and the architecture of Entity Framework, including the Entity Data Model (EDM) and its components.

Uploaded by

Mohamad Iliyas
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/ 39

UNIT-III

Entity Framework

Entity Framework is an open-source ORM framework for .NET


applications supported by Microsoft. It enables developers to work
with data using objects of domain specific classes without focusing
on the underlying database tables and columns where this data is
stored. With the Entity Framework, developers can work at a higher
level of abstraction when they deal with data, and can create and
maintain data-oriented applications with less code compared with
traditional applications.

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 Latest Versions


Microsoft introduced Entity Framework in 2008 with .NET Framework
3.5. Since then, it released many versions of Entity Framework.
Currently, there are two latest versions of Entity Framework: EF 6
and EF Core. The following table lists important difference between
EF 6 and EF Core.

Entity Framework Architecture


The following figure shows the overall architecture of the Entity
Framework.

Let's look at the components of the architecture individually.

EDM (Entity Data Model): EDM consists of three main parts -


Conceptual model, Mapping and Storage model.
Conceptual Model: The conceptual model contains the model
classes and their relationships. This will be independent from your
database table design.

Storage Model: The storage model is the database design model


which includes tables, views, stored procedures, and their
relationships and keys.

Mapping: Mapping consists of information about how the conceptual


model is mapped to the storage model.

LINQ to Entities: LINQ-to-Entities (L2E) is a query language used


to write queries against the object model. It returns entities, which
are defined in the conceptual model. You can use your LINQ skills
here.

Entity SQL: Entity SQL is another query language (For EF 6 only)


just like LINQ to Entities. However, it is a little more difficult than
L2E and the developer will have to learn it separately.

Object Service: Object service is a main entry point for accessing


data from the database and returning it back. Object service is
responsible for materialization, which is the process of converting
data returned from an entity client data provider (next layer) to an
entity object structure.

Entity Client Data Provider: The main responsibility of this layer is


to convert LINQ-to-Entities or Entity SQL queries into a SQL query
which is understood by the underlying database. It communicates
with the ADO.Net data provider which in turn sends or retrieves data
from the database.

ADO.Net Data Provider: This layer communicates with the


database using standard ADO.Net.

How Entity Framework Works?


Here, you will see an overview of how entity framework works.

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.

Entity Data Model


The very first task of EF API is to build an Entity Data Model (EDM).
EDM is an in-memory representation of the entire metadata:
conceptual model, storage model, and mapping between them.
Conceptual Model: EF builds the conceptual model from your
domain classes, context class, default conventions followed in your
domain classes, and configurations.

Storage Model: EF builds the storage model for the underlying


database schema. In the code-first approach, this will be inferred
from the conceptual model. In the database-first approach, this will
be inferred from the targeted database.

Mappings: EF includes mapping information on how the conceptual


model maps to the database schema (storage model).

EF performs CRUD operations using this EDM. It uses EDM in building


SQL queries from LINQ queries, building INSERT, UPDATE, and
DELETE commands, and transform database result into entity
objects.

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.

The following figure illustrates the basic workflow.

Let's understand the above EF workflow:

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.

What is object-relational mapping (ORM)?


Object-relational mapping (ORM) is a way to align programming code
with database structures. ORM uses metadata descriptors to create a layer
between the programming language and a relational database. It thus
connects object-oriented program (OOP) code with the database and
simplifies the interaction between relational databases and OOP
languages.

The idea of ORM is based on abstraction. The ORM mechanism makes it


possible to address, access and manipulate objects without having to
consider how those objects relate to their data sources. ORM lets
programmers maintain a consistent view of objects over time, even as the
sources that deliver them, the sinks that receive them and the applications
that access them change.

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

Entity Framework - Data Annotations


DataAnnotations is used to configure the classes which will highlight the most commonly
needed configurations. DataAnnotations are also understood by a number of .NET
applications, such as ASP.NET MVC which allows these applications to leverage the same
annotations for client-side validations. DataAnnotation attributes override default
CodeFirst conventions.

System.ComponentModel.DataAnnotations includes the following attributes that


impacts the nullability or size of the column.

Key
Timestamp

ConcurrencyCheck

Required

MinLength

MaxLength

StringLength

System.ComponentModel.DataAnnotations.Schema namespace includes the


following attributes that impacts the schema of the database.

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

The property will map to a primary key column in the database.

The Student, Course and Enrollment classes follow this convention.

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.

public class Student {

[Key]
public int StdntID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }

public virtual ICollection<Enrollment> Enrollments { 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.

public class DrivingLicense {

[Key, Column(Order = 1)]


public int LicenseNumber { get; set; }
[Key, Column(Order = 2)]
public string IssuingCountry { get; set; }
public DateTime Issued { get; set; }
public DateTime Expires { get; set; }
}

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.

It's more common to use rowversion or timestamp fields for concurrency


checking.
Rather than using the ConcurrencyCheck annotation, you can use the more
specific TimeStamp annotation as long as the type of the property is byte array.

You can only have one timestamp property in a given class.

Let’s take a look at a simple example by adding the TimeStamp property to the Course
class −

public class Course {

public int CourseID { get; set; }


public string Title { get; set; }
public int Credits { get; set; }
[Timestamp]
public byte[] TStamp { get; set; }

https://www.tutorialspoint.com/entity_framework/entity_framework_data_annotations.htm 4/19
12/16/24, 2:02 PM Entity Framework - Data Annotations

public virtual ICollection<Enrollment> Enrollments { get; set; }


}

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.

Let’s take a look at a simple example of how ConcurrencyCheck works by adding it to


the Title property in Course class.

public class Course {

public int CourseID { get; set; }


[ConcurrencyCheck]
public string Title { get; set; }
public int Credits { get; set; }
[Timestamp, DataType("timestamp")]
public byte[] TimeStamp { get; set; }

public virtual ICollection<Enrollment> Enrollments { get; set; }


}

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.

exec sp_executesql N'UPDATE [dbo].[Courses]


SET [Title] = @0
WHERE (([CourseID] = @1) AND ([Title] = @2))
',N'@0 nvarchar(max) ,@1 int,@2 nvarchar(max) ',@0=N'Maths',@1=1,@2=N'Calculu
go

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.

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; }

public virtual ICollection<Enrollment> Enrollments { get; set; }


}

As seen in the above example, Required attribute is applied to FirstMidName and


LastName. So, Code First will create a NOT NULL FirstMidName and LastName columns
in the Students table as shown in the following image.

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.

public class Course {

public int CourseID { get; set; }


[ConcurrencyCheck]
[MaxLength(24)]
public string Title { get; set; }
public int Credits { get; set; }

public virtual ICollection<Enrollment> Enrollments { get; set; }


}

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.

public class Course {

public int CourseID { get; set; }


[ConcurrencyCheck]
[MaxLength(24) , MinLength(5)]
public string Title { get; set; }
public int Credits { get; set; }

public virtual ICollection<Enrollment> Enrollments { get; set; }


}

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.

public class Course {

public int CourseID { get; set; }


[StringLength (24)]
public string Title { get; set; }
public int Credits { get; set; }

public virtual ICollection<Enrollment> Enrollments { get; set; }


}

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.

Table attribute overrides this default convention.

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; }

public virtual ICollection<Enrollment> Enrollments { 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.

[Table("StudentsInfo", Schema = "Admin")]


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; }

public virtual ICollection<Enrollment> Enrollments { 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 −

Column attribute overrides the default convention.

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.

public class Student {

public int ID { get; set; }


public string LastName { get; set; }
[Column("FirstName")]
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }

https://www.tutorialspoint.com/entity_framework/entity_framework_data_annotations.htm 11/19
12/16/24, 2:02 PM Entity Framework - Data Annotations

public virtual ICollection<Enrollment> Enrollments { get; set; }


}

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.

By default, the index will be named IX_<property name>

Let’s take a look at the following code in which Index attribute is added in Course class
for Credits.

public class Course {


public int CourseID { get; set; }
public string Title { get; set; }
[Index]
public int Credits { get; set; }

public virtual ICollection<Enrollment> Enrollments { get; set; }


}

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

public class Course {


public int CourseID { get; set; }
[Index(IsUnique = true)]

public string Title { get; set; }


[Index]

public int Credits { get; set; }


public virtual ICollection<Enrollment> Enrollments { get; set; }
}

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.

public class Enrollment {


public int EnrollmentID { get; set; }
public int CourseID { get; set; }
public int StudentID { get; set; }
public Grade? Grade { get; set; }

public virtual Course Course { get; set; }


public virtual Student Student { get; set; }
}

public class Student {


[Key]
public int StdntID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }

public virtual ICollection<Enrollment> Enrollments { get; set; }


}

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.

public class Enrollment {


public int EnrollmentID { get; set; }
public int CourseID { get; set; }
public int StudentID { get; set; }

public Grade? Grade { get; set; }


public virtual Course Course { get; set; }
[ForeignKey("StudentID")]

public virtual Student Student { get; set; }


}

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.

public class Student {


[Key]
public int StdntID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }

public DateTime EnrollmentDate { get; set; }


[NotMapped]

public int FatherName { get; set; }


public virtual ICollection<Enrollment> Enrollments { get; set; }
}

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.

public class Enrollment {


public int EnrollmentID { get; set; }
public int CourseID { get; set; }
public int StudentID { get; set; }
public Grade? Grade { get; set; }

public virtual Course CurrCourse { get; set; }


public virtual Course PrevCourse { get; set; }
public virtual Student Student { get; set; }
}

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.

public class Course {

public int CourseID { get; set; }


public string Title { get; set; }
[Index]

public int Credits { get; set; }


public virtual ICollection<Enrollment> CurrEnrollments { get; set; }
public virtual ICollection<Enrollment> PrevEnrollments { get; set; }
}

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.

public class Course {

public int CourseID { get; set; }


public string Title { get; set; }
[Index]

public int Credits { get; set; }


[InverseProperty("CurrCourse")]

public virtual ICollection<Enrollment> CurrEnrollments { get; set; }


[InverseProperty("PrevCourse")]

https://www.tutorialspoint.com/entity_framework/entity_framework_data_annotations.htm 18/19
12/16/24, 2:02 PM Entity Framework - Data Annotations

public virtual ICollection<Enrollment> PrevEnrollments { get; set; }


}

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

Entity Framework - Code First Approach


The Entity Framework provides three approaches to create an entity model and each one
has their own pros and cons.

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

Why Code First?

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.

Visual Studio 2013 (.net framework 4.5.2) or later version.

MS SQL Server 2012 or latter.

Entity Framework via NuGet Package.

Explore our latest online courses and learn new skills at your own pace. Enroll and
become a certified expert to boost your career.

Install EF via NuGet Package


Step 1 − First, create the console application from File → New → Project…

Step 2 − Select Windows from the left pane and Console Application from the template
pane.

Step 3 − Enter EFCodeFirstDemo as the name and select OK.

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”.

After installation, EntityFramework.dll will be included in your project, as shown in the


following image.

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

Now you are ready to start working on 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

Entity Framework - Database First Approach


In this chapter, let us learn about creating an entity data model with 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 1 − Let’s create a new console project with DatabaseFirstDemo name.

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.

Step 5 − Select EF Designer from database and click Next button.

https://www.tutorialspoint.com/entity_framework/entity_database_first_approach.htm 2/6
12/16/24, 1:59 PM Entity Framework - Database First Approach

Step 6 − Select the existing database and click Next.

Step 7 − Choose Entity Framework 6.x and click Next.

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 {

static void Main(string[] args) {

using (var db = new UniContextEntities()) {

var query = from b in db.Students


orderby b.FirstMidName select b;

Console.WriteLine("All All student in the database:");

foreach (var item in query) {


Console.WriteLine(item.FirstMidName +" "+ item.LastName);
}

Console.WriteLine("Press any key to exit...");


Console.ReadKey();
}
}
}
}

When the above program is executed, you will receive the following output −

All student in the database:


Ali Khan
Arturo finand
Bill Gates
Carson Alexander
Gytis Barzdukas
Laura Norman
Meredith Alonso
Nino Olivetto
Peggy Justice
Yan Li
Press any key to exit...

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

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