Site icon GlaptTech

Data Access and Entity Framework Core

Chapter 8: Data Access and Entity Framework Core

8.1 Overview of Data Access Options in ASP.NET Core
ASP.NET Core provides various options for data access, including raw ADO.NET, Dapper, and Entity Framework Core (EF Core). These options differ in terms of complexity, flexibility, and abstraction level.

In this chapter, we will focus on using Entity Framework Core as the data access technology. EF Core is an Object-Relational Mapping (ORM) framework that simplifies database access by mapping database tables to entity classes and providing a high-level API for performing database operations.

8.2 Using Entity Framework Core for Data Access
EF Core is a lightweight, extensible, and cross-platform ORM framework that supports a wide range of database providers. It provides a rich set of features for mapping entities to database tables, querying data, and performing CRUD operations.

To use EF Core in your ASP.NET Core application, you need to install the Microsoft.EntityFrameworkCore NuGet package and configure a database provider.

8.3 Configuring Database Providers and Connection Strings
EF Core supports multiple database providers, including SQL Server, SQLite, MySQL, PostgreSQL, and more. You can choose the provider based on your database requirements and install the corresponding NuGet package.

To configure the database provider and connection string, you need to modify the appsettings.json file and register the database context in the Startup.cs file.

Here’s an example of configuring a SQL Server provider and connection string:

"ConnectionStrings": {
  "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=MyDatabase;Trusted_Connection=True;MultipleActiveResultSets=true"
}

In the Startup.cs file:

public void ConfigureServices(IServiceCollection services)
{
    // Other service configurations

    services.AddDbContext<MyDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}

8.4 Working with Database Context and Entities
The database context represents a session with the database and acts as a gateway to perform database operations. It encapsulates the database connection, transaction management, and entity sets.

To work with EF Core, you need to create a derived class from DbContext and define DbSet properties for your entities.

Here’s an example of a simple database context class:

public class MyDbContext : DbContext
{
    public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
    {
    }

    public DbSet<User> Users { get; set; }
}

In this example, MyDbContext derives from DbContext, and a DbSet<User> property is defined for the User entity.

8.5 Implementing Database Operations (CRUD) with EF Core
EF Core provides a rich API for performing CRUD (Create, Read, Update, Delete) operations on entities.

Here’s an example of implementing CRUD operations with EF Core:

public class UserRepository : IUserRepository
{
    private readonly MyDbContext _dbContext;

    public UserRepository(MyDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public async Task<User> GetUserById(int id)
    {
        return await _dbContext.Users.FindAsync(id);
    }

    public async Task<IEnumerable<User>> GetAllUsers()
    {
        return await _dbContext.Users.ToListAsync();
    }

    public async Task CreateUser(User user)
    {
        _dbContext.Users.Add(user);
        await _dbContext.SaveChangesAsync();
    }

    public async Task UpdateUser(User user)
    {
        _dbContext.Users.Update(user);
        await _dbContext.SaveChangesAsync();
    }

    public async Task DeleteUser(User user)
    {
        _dbContext.Users.Remove(user);
        await _dbContext.SaveChangesAsync();
    }
}

In this example, a UserRepository class is responsible for performing CRUD operations on the User entity. The MyDbContext instance is injected into the repository’s constructor using dependency injection.

By utilizing the EF Core API, you can easily query, insert, update, and delete entities from the database.

Chapter 8 provides a comprehensive explanation of data access using Entity Framework Core in ASP.NET Core. By leveraging EF Core, you can simplify database access, configure database providers and connection strings, work with database context and entities, and implement CRUD operations efficiently.

Exit mobile version