Saturday 17 August 2024

Entity Framework Core

Entity Framework Core (EF Core) is an open-source, lightweight, and extensible Object-Relational Mapper (ORM) developed by Microsoft. It is designed to work with .NET applications to facilitate data access and manipulation using object-oriented programming concepts.

Here are some key features and concepts of EF Core:

  1. Object-Relational Mapping (ORM): EF Core helps in mapping .NET objects to database tables, allowing developers to interact with a database using strongly-typed C# classes rather than writing raw SQL queries.

  2. Database Providers: EF Core supports a variety of database systems through different database providers, including Microsoft SQL Server, SQLite, PostgreSQL, MySQL, and more. Each provider contains the necessary implementation for working with a specific type of database.

  3. LINQ Queries: EF Core allows developers to write queries using Language Integrated Query (LINQ), which is then translated into the appropriate SQL queries by the framework.

  4. Migrations: EF Core provides a migrations feature that helps manage database schema changes over time. It allows developers to create, modify, and update database schemas in a controlled manner.

  5. Change Tracking: EF Core tracks changes made to entities and automatically generates the necessary SQL commands to update the database when SaveChanges is called.

  6. Caching and Performance: EF Core includes various performance optimization features, such as caching and lazy loading, to improve the efficiency of data access operations.

  7. NoSQL Support: Although EF Core is primarily used with relational databases, it also has some support for NoSQL databases, particularly through custom providers and extensions.

  8. Cross-Platform: EF Core is cross-platform and can be used with .NET Core, making it suitable for developing applications that run on different operating systems, including Windows, Linux, and macOS.

EF Core is part of the larger .NET ecosystem and is commonly used in ASP.NET Core applications to handle data access. It provides a high-level, abstracted way to interact with databases, allowing developers to focus more on business logic rather than database-related concerns.

EF Core Database First Approach
Sometimes we may have an existing database. When we have a database and the database tables already, we use the database first approach. With the database first approach, EF Core creates the DBContext and Domain classes based on the existing database schema.

EF Core Database Providers
EF Core supports many relational and even non relational databases. EF Core is able to do this by using plug-in libraries called the database providers. These database providers are available as NuGet packages. 

List of EF Core Database Providers

https://docs.microsoft.com/en-us/ef/core/providers/

A database provider, usually sits between EF Core and the database it supports. The database provider contains the functionality specific to the database it supports. Functionality that is common to all the databases is in the EF Core component. Functionality that is specific to a database, for example, Microsoft SQL Server specific functionality is with-in the SQL Server provider for EF Core. 

To install Entity Framework Core and to be able to use SQL server as the database for your application, you need to install the following nuget packages.

Microsoft.EntityFrameworkCore.SqlServer - This nuget package contains SQL Server specific functionality

Microsoft.EntityFrameworkCore.Relational - This nuget package contains functionality that is common to all relational databases

Microsoft.EntityFrameworkCore - This nuget package contains common entity frameowrk core functionality

When we install Microsoft.EntityFrameworkCore.SqlServer package, it also installs all the other dependant nuget packages automatically. 

DbContext in entity framework core

One of the very important classes in Entity Framework Core is the DbContext class. This is the class that we use in our application code to interact with the underlying database. It is this class that manages the database connection and is used to retrieve and save data in the database.

To use the DbContext class in our application We create a class that derives from the DbContext class.
DbContext class is in Microsoft.EntityFrameworkCore namespace.

public class AppDbContext : DbContext
{ }


For the DbContext class to be able to do any useful work, it needs an instance of the DbContextOptions class.
 The DbContextOptions instance carries configuration information such as the connection string, database provider to use etc.
To pass the DbContextOptions instance we use the constructor as shown in the example below.

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions[AppDbContextoptions)
        : base(options)
    {
    }
    public DbSet[EmployeeEmployees { getset; }
}


The DbContext class includes a DbSet[TEntity] property for each entity in the model.

Using sql server with entity framework core
When using Entity Framework Core, one of the important things that we need to configure is the database provider that we plan to use.  Click here

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContextPool[AppDbContext](options =>
      options.UseSqlServer(_config.GetConnectionString("EmployeeDBConnection")));

    services.AddMvc().AddXmlSerializerFormatters();
    services.AddTransient[IEmployeeRepositoryMockEmployeeRepository]();
}


We want to configure and use Microsoft SQL Server with entity framework core. We usually specify this configuration in ConfigureServices() method in Startup.cs file.

We can use either AddDbContext() or AddDbContextPool() method to register our application specific DbContext class with the ASP.NET Core dependency injection system.

The difference between AddDbContext() and AddDbContextPool() methods is, AddDbContextPool() method provides DbContext pooling.

With DbContext pooling, an instance from the DbContext pool is provided if available, rather than creating a new instance.

DbContext pooling is conceptually similar to how connection pooling works in ADO.NET.

From a performance standpoint AddDbContextPool() method is better over AddDbContext() method.

UseSqlServer() extension method is used to configure our application specific DbContext class to use Microsoft SQL Server as the database.

To connect to a database, we need the database connection string which is provided as a parameter to UseSqlServer() extension method

Instead of hard-coding the connection string in application code, we store it appsettings.json configuration file.

{
    "ConnectionStrings": {
      "EmployeeDBConnection": "server=(localdb)\\MSSQLLocalDB;database=EmployeeDB;
Trusted_Connection=true"
    }
  }


To read connection string from appsettings.json file we use IConfiguration service GetConnectionString() method.

Entity framework core migrations- Click hereClick here

Migration is an entity framework core feature that keeps the database schema and our application model classes (also called entity class) in sync.

If you have not executed at-least the initial migration in your application you might get the following SqlException

SqlException: Cannot open database "EmployeeDB" requested by the login.

This is because we do not have the database created yet. One way to create the database is by 

  • Creating a migration first and then
  • Executing that migration

We will be using the following commands to work with migrations in entity framework core.

Add-Migration: Adds a new migration
Update-Database: Updates the database to a specified migration
Remove-Migration: It only removes one migration at a time and that too only the latest migration that is not yet applied to the database. If all the migrations are already applied, executing Remove-Migration command throws the following exception.

Creating a Migration in Entity Framework Core
The following command creates the initial migration. InitialCreate is the name of the migration.

Add-Migration InitialCreate


When the above command completes, you will see a file in the "Migrations" folder that contains the name InitialCreate.cs. This file has the code required to create the respective database tables.

Update-Database in Entity Framework Core
We need to execute the migration code to create the tables. If the database does not exist already, it creates the database and then the database tables. For updating the database, we use Update-Database command. To the Update-Database command we may pass the migration name we want to execute. If no migration is specified, the command by default executes the last migration.

Entity framework core seed data Click here
If you are using Entity Framework Core 2.1 or later there is a new method of seeding database data. In your application DbContext class, override OnModelCreating() method.

HasData() method configures entity to have the specified seed data.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity[Employee]().HasData(
        new Employee
        {
            Id = 1,
            Name = "Mark",
            Department = Dept.IT,
            Email = "mark@pragimtech.com"
        }
    );
}


0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (8) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (17) Entity Framework (3) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (10) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives