Unit-2
Unit-2
It is designed to work with .NET Core and .NET Framework applications and provides an Object-
Relational Mapper (ORM) that enables .NET developers to work with a database using .NET objects.
It eliminates most of the data-access code that developers usually need to write.
What is ORM?
ORM stands for Object-Relational Mapping, a programming technique that allows developers to convert
data between incompatible systems, specifically between Object-Oriented Programming Languages (such
as C#, Java, etc.) and Relational Databases (such as SQL Server, MySQL, Oracle, etc.).
• ORM allows developers to work with data in terms of objects rather than tables and columns. That
means ORM automatically creates classes based on database tables, and vice versa is also true.
• It can also generate the necessary SQL to create the database based on the classes.
• As developers, we mainly work with data-driven applications, and the ORM Framework can
generate the necessary SQL (to perform the database CRUD operation) that the underlying database
can understand.
• It takes responsibility for opening the connection, executing the command, handling the
transaction to ensure data integrity, closing the connection, etc. So, in simple words, we can say
that the ORM Framework eliminates the need for most of the data access code we generally write.
Let’s understand why we need to use the ORM Framework with an example. Suppose we want to develop
an application to manage the students of a college. To do this, we may need to create classes such as Student,
Department, Address, etc. Technically, we call these classes Domain classes or business objects.
Without using an ORM Framework like Entity Framework or EF Core, we have to write lots of data access
code to perform the CRUD operations, i.e., store and retrieve the Student, Department, and Address data
from the underlying database tables.
For example, to perform CRUD operations, i.e., read, insert, update, or delete from a database table, we
generally need to write the required SQL statements, which the underlying database should understand.
Again, when we want to read the data from the database into our application, we also have to write some
custom logic to map the data to our model classes like Student, Department, Address, etc. This is a common
task that we do in almost every application.
An ORM Framework like Entity Framework or EF Core can do all of the above for us and saves a lot of
time if we provide the required information to the ORM Framework. The ORM Framework sits between our
application code and the Database. It eliminates the need for most custom data-access codes we usually
write without an ORM. For a better understanding, please have a look at the following diagram:
• Cross-Platform: EF Core works on various platforms, including Windows, macOS, and
Linux.
• Extensible: EF Core is highly customizable and extensible, allowing developers to use
custom conventions, third-party plugins, and additional database providers.
• Performance: EF Core has been optimized for performance, making it suitable for small,
medium, and large-scale applications.
• Integration: EF Core integrates easily with .NET Core, making it the first choice for data
access in .NET applications.
• Flexibility: EF Core supports various database providers, which allows it to work with
different database systems.
• Modern Features: EF Core includes features like asynchronous operations, better support
for LINQ queries, and improved support for complex types and relationships.
*DbContext class
In Entity Framework Core, the DbContext class is a central part of the framework.
It represents a session with the database and is used to interact with the database through querying,
saving, and managing data.
In Entity Framework Core, a database connection string is essential for establishing a connection between
your application and the database.
It contains details like the server name, database name, credentials, and other settings
Using appsettings.json:
Store the connection string in the appsettings.json file for better maintainability:
{
"ConnectionStrings": {
"DefaultConnection":
"Server=(localdb)\\MSSQLLocalDB;Database=YourDatabaseName;Trusted_Connection=True;"
}
}
CRUD (Create, Read, Update, Delete) operations are fundamental in ASP.NET Core MVC for managing
data.
Step-1) Install these 3 packages..
"ConnectionStrings": {
"DefaultConnection":
"Server=SANGOLA123\\SQLEXPRESS;Database=MySTUDDB;Trusted_Connection=True;TrustServerCertificat
e=True;"
builder.Services.AddDbContext<ApplicationDBContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
Generate a scaffolded controller to handle CRUD operations using Entity Framework Core:
In Entity Framework Core, entity states represent the state of an entity in relation to the database and the
DbContext.
These states help EF Core determine what actions to perform on the database when SaveChanges() is
called.
1. Added:
o The entity is being tracked by the context but does not yet exist in the database.
o EF Core will issue an INSERT command for this entity during SaveChanges().
2. Unchanged:
o The entity is being tracked and exists in the database, but its property values have not been
modified.
o EF Core will not issue any database commands for entities in this state.
3. Modified:
o The entity is being tracked and exists in the database, but some or all of its property values
have been changed.
o EF Core will issue an UPDATE command for the modified properties during SaveChanges().
4. Deleted:
o The entity is being tracked and exists in the database, but it has been marked for deletion.
o EF Core will issue a DELETE command for this entity during SaveChanges().
5. Detached:
o The entity is not being tracked by the context.
o EF Core will not perform any database operations on detached entities.
How to Check or Set Entity States:
You can use the EntityEntry.State property to check or modify the state of an entity:
In Entity Framework Core, Data Annotation Attributes are used to configure the model by decorating
classes and properties with metadata.
1. Table Attribute
2. Column Attribute
3. Key Attribute
[Key]
public int EmployeeId { get; set; }
4. ForeignKey Attribute
[ForeignKey("DepartmentId")]
public Department Department { get; set; }
5. Index Attribute
6. InverseProperty Attribute
7. NotMapped Attribute
[NotMapped]
public string FullName { get; set; }
8. Required Attribute
[Required]
public string Name { get; set; }
[MaxLength(50)]
[MinLength(5)]
public string Name { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int EmployeeId { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; }
[ConcurrencyCheck]
public string Name { get; set; }
Entity Framework Core (EF Core) simplifies managing relationships between entities in your data model.
In Entity Framework Core (EF Core), relationships define how entities (classes) are related to each other
in your data model.
1. One-to-One Relationship
2. One-to-Many Relationship
3. Many-to-Many Relationship
A Student entity can be associated with many Course entities, and vice versa:
*Self-Referencing Relationship
A self-referencing relationship in Entity Framework Core is when an entity has a relationship with
itself.
OR
A self-referencing relationship in Entity Framework Core occurs when an entity has a relationship with
another instance of the same entity type.
This is useful for scenarios like organizational hierarchies, threaded comments, categories with
subcategories, etc.
This is used for modeling hierarchical data, such as an Employee entity where each employee can have a
manager who is also an employee.
Explanation:
• ManagerId: Acts as the foreign key referencing the EmployeeId of the manager.
• Manager: Navigation property pointing to the manager.
• Subordinates: Collection navigation property representing employees managed by this employee.
Configuring in DbContext
This setup allows you to query hierarchical data, such as retrieving all subordinates of a specific manager or
finding the manager of an employee.
Asynchronous programming in Entity Framework Core (EF Core) allows you to perform database
operations without blocking the main thread.
This is particularly useful for improving the responsiveness of applications, especially in scenarios like web
applications or UI-based apps. Here’s a quick overview:
Important Notes
Disconnected entities in Entity Framework Core (EF Core) refer to entities that are no longer tracked by
a DbContext instance.
This typically happens in scenarios like web applications, where entities are fetched from the database,
manipulated outside the scope of the DbContext, and then returned for further processing.
Managing disconnected entities requires explicit state management when reattaching them to a new
DbContext.
Key Concepts:
1. Connected Entities: Actively tracked by the DbContext. Changes are automatically detected and
saved.
2. Disconnected Entities: Not tracked by any DbContext. Their state must be explicitly set when
reattaching.
Suppose you fetch a Product entity, modify it in a client application, and then save it back to the database.
Stored procedures in Entity Framework Core allow you to execute predefined SQL commands directly
from your application, which can be useful for complex queries or operations that require optimized
performance.
• Using FromSqlRaw: You can retrieve data from stored procedures using
DbSet<TEntity>.FromSqlRaw().
Example:
• Executing Non-Query Stored Procedures: If your stored procedure performs insert, update, or
delete operations, use ExecuteSqlRaw():
• Limitations:
o Stored procedures must return all columns of an entity type.
o They cannot return related data (i.e., no joins).
o Insert, update, and delete procedures cannot be mapped directly to entities.
"ConnectionStrings": {
"MyConn":
"Server=SAANVI\\SQLEXPRESS;Database=MYDB;Trusted_Connection=True;TrustServerCertificate=Tr
ue;"
},
builder.Services.AddDbContext<StudentDBContext>(options=>options.UseSqlServer(builder.Configuratio
n.GetConnectionString("MyConn")));
Step-6) Create the Controller In your Controller, call the method to fetch data using the stored
procedure.
<h1>Index</h1>
@model List<Student>
What is a Transaction?
A transaction is a unit of work where all operations must succeed, or none are applied.
Transactions in Entity Framework Core ensure that multiple database operations are executed as a single
unit, meaning they either all succeed or all fail, maintaining data integrity.
EF Core uses transactions automatically by default when SaveChanges() is called — but you can
manually control them when needed.
context.SaveChanges();
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
}
4. Savepoints: EF Core automatically creates savepoints within transactions, allowing partial rollbacks.
class Program
{
static void Main()
{
using var context = new AppDbContext();
using var transaction = context.Database.BeginTransaction();
try
{
var order1 = new Order { ProductName = "Laptop", Quantity = 1 };
var order2 = new Order { ProductName = "Mouse", Quantity = 2 };
context.Orders.Add(order1);
context.Orders.Add(order2);
context.SaveChanges();
transaction.Commit();
Console.WriteLine("Transaction committed successfully.");
}
catch (Exception ex)
{
transaction.Rollback();
Console.WriteLine($"Transaction rolled back due to error: {ex.Message}");
}
}
}
Explanation:
• Migrations in Entity Framework Core allow you to incrementally update your database schema to
match changes in your application's data model, without losing existing data.
• It's part of the Code-First approach, where your C# classes drive the shape of your database.
Database seeding in Entity Framework Core allows you to populate your database with initial data when
it's created or migrated.
This is useful for setting up default values, test data, or essential records.
This data is applied when running dotnet ef migrations add and dotnet ef database update.
1. Code-First Approach: In this approach, the data model (classes) is created first, and Entity
Framework Core generates the database schema based on the model.
2. Database-First Approach: This approach is used when an existing database is available. Entity
Framework Core can generate the data model (classes) based on the database schema.
1)EF Core Code First Approach:
In the EF Core Code First Approach, first, we need to create our application domain classes, such as Student,
Branch, Address, etc., and a special class (called DBContext Class) that derives from the Entity
Framework Core DbContext class.
Developers can configure relationships, constraints, and database mappings using Data Annotations and
Fluent API. Then, based on the application domain classes and DBContext class, the EF Core creates the
database and related tables. For a better understanding, please have a look at the following diagram.
Example-
Step-1) Install EF Core NuGet Package: Add the required Entity Framework Core packages to your
project:
Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Design
using System.ComponentModel.DataAnnotations;
namespace CodeFirstEF.Models
{
public class Student
{
[Key]
public int rollnum { get; set; }
public string name { get; set; }
public int mbnum { get; set; }
}
}
---------------------------------------------------------------------------------------------
using Microsoft.EntityFrameworkCore;
namespace CodeFirstEF.Models
{
public class StudentDBContext:DbContext
{
public StudentDBContext(DbContextOptions options):base(options)
{
}
public DbSet<Student> Students { get; set; }
}
}
Step-3) Configure the Connection String
appsettings.json:
"ConnectionStrings": {
"MyConn":
"Server=SAANVI\\SQLEXPRESS;Database=STUD;Trusted_Connection=True;TrustServerCertificate=Tru
e;"
},
builder.Services.AddDbContext<StudentDBContext>(options=>options.UseSqlServer(builder.Configuratio
n.GetConnectionString("MyConn")));
Now that we have the model and DbContext, let’s create a migration to generate the database schema.
PM> Update-Database
Use the EF Core Database First Approach if you have an existing database and database tables are already
there.
In the database-first approach, the EF Core creates the DBContext and Domain Classes based on the
existing database schema.
This approach is suitable for scenarios where the application code does not control the database schema or
when working with existing databases. For a better understanding, please have a look at the following
diagram.
So, the Database First approach starts with an existing database schema. EF Core generates the domain
classes that map to the database tables. This approach is suitable for applications that need to work with an
existing database.
Example-
Here's an example of SQL code to create a table named students in SQL Server:
Step-2) Create ASP.Net Core MVC Application and Install following 3 Packages
Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Design
Run the following command in the Package Manager Console to generate models and DbContext based on
an existing database:
Scaffold-DbContext
"Server=SAANVI\\SQLEXPRESS;Database=STUD;Trusted_Connection=True;TrustServerCertificate=Tru
e;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models