Entity framework_ORM_Database Integration- Asp.net
Entity framework_ORM_Database Integration- Asp.net
Entity Framework (EF) serves as a bridge between your application and the
database. It provides the following functionalities:
1. Mapping: EF maps your .NET classes to database tables and your class
properties to columns in those tables.
2. Queries: EF allows you to write LINQ (Language Integrated Query)
queries in C#, which EF translates into SQL queries that are executed
against the database.
3. Change Tracking: EF tracks changes made to the objects during runtime
and automatically generates the necessary SQL commands to update the
database.
4. Migrations: EF provides a way to handle changes to the database schema
over time through a process called migrations.
● Approaches with ORM :
When using an ORM, there are three main approaches to work with the database
schema:
1. Code-First Approach:
○ In this approach, you start by writing the classes (code) that
represent the data model. The ORM then generates the database
schema based on these classes.
○ Example: Entity Framework's Code-First approach.
2. Database-First Approach:
○ In this approach, you start with an existing database. The ORM
generates classes (entities) based on the existing database schema.
○ Example: Entity Framework's Database-First approach.
Note : Code-First is a specific approach under ORM where the database schema
is generated based on the classes you define in your code.
Let's walk through a simple example to illustrate how EF works for database
integration:
{
public int Id { get; set; }
public
ApplicationDbContext(DbContextOptions<ApplicationDbContext>
options)
: base(options)
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("D
efaultConnection")));
app.MapControllers();
app.Run();
{
"ConnectionStrings": {
"DefaultConnection": "YourConnectionStringForMSSQLOrPostgreSQL"
},
"DatabaseProvider": "SqlServer" // or "PostgreSQL"
}
6. Implement CRUD Operations
_context = context;
_context.Products.Add(product);
await _context.SaveChangesAsync();
// Read products
// Update a product
_context.Products.Update(product);
await _context.SaveChangesAsync();
// Delete a product
if (product != null)
_context.Products.Remove(product);
await _context.SaveChangesAsync();
}
5. Apply Migrations
Summary:
Note : By using Entity Framework as an ORM, you can interact with the
database in an object-oriented way, making your code cleaner and reducing
the need to write raw SQL queries.
Database Configuration
● Define a DbContext.cs class to manage your database sessions within the Data
directory.
using dependencyInjection.Models;
using Microsoft.EntityFrameworkCore;
● In ASP.NET Core 8.0, the Program.cs file combines the setup that was previously split
between Startup.cs and Program.cs.
app.Run();
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"ConnectionStrings": {
"DefaultConnection":
"Server=LAPTOP-2C0VA32U\\MSSQLSERVER_ASUS;Database=ProductDb;Integrated
Security=True;MultipleActiveResultSets=True;TrustServerCertificate=True;"
},
"DatabaseProvider": "SqlServer" // or "PostgreSQL"
}
namespace YourNamespace.Repositories
{
public class ProductRepository : IProductRepository
{
private readonly YourDbContext _context;
// Get product by ID
public Product GetProductById(int productId)
{
return _context.Products.Find(productId);
}
// Delete a product by ID
public void DeleteProduct(int productId)
{
var product = _context.Products.Find(productId);
if (product != null)
{
_context.Products.Remove(product);
Save();
}
}
7. Apply Migrations
orderby p.Name
Characteristics:
● It uses keywords like from, where, select, orderby, etc., similar to SQL.
● It can be more intuitive for those familiar with SQL.
● Suitable for simpler queries, but it may become cumbersome for more complex
operations.
.ToList();
Characteristics:
● It uses method calls like Where, OrderBy, Select, etc., with lambda expressions
to define operations.
● Often more concise and flexible, especially for complex queries.
● Allows for fluent chaining of methods.