# What is Entity Framework Core?
It is a database interaction framework (by .NET), mapping code to databases for simplified data access.
Entity Framework Core (EF Core)
is an Object-Relational Mapper (ORM).
So, developers don’t have to write any SQL-statements manually.
# DB-Migration: How it works
It is a structured way of evolving the db over time, highlighting changes in application’s data model.
How a db-migration works
- Create/Modify entity classes
- changes to data model - changes represent how data is structured in application.
- generate migration files
- devs use migration tool (EF Core) to generate migration files based on changes made to the entity class.
- these migration files contain instructions for updating the db schema.
- Review & customize migration files
- devs can review & check these automatically generated files.
- devs can customize migration files if needed.
- Apply migrations
- devs use migration tool to apply changes to db. This process executes SQL-statements for deleting, creating, modifying db-objects
- Update db
- migration tool updates a specific table in db
The dev describes any entity classes. Changes represent how data is structured in the application.
# Prompts: Add Migration; Update DB
# : DbContext
Key component for an application to communicate with a db properly. It represents a session with the db.
The DbContext
class is a part of the DbContext API, which is a set of APIs for interacting with a db using a high-level, object-oriented approach.
# How to use DbContext
This creates some SQL-statements. You can review these statements by adding this line in OnConfiguring()
# DbSet<…>
Mapping between application’s entity & corresponding table in db. We tell EF, that the User class corresponds to a db table.
The DbSet allows us to do db operations on the Users property (CRUD)
# Code First Principle
In the context of EF Core:
-
Code definition: (in code) devs start by defining classes to represent entities (objects)
-
attributes: (in code) details such as table names, primary keys, relationships are specified
-
DB generation: db schema is generated automatically using ORM framework.
- Based on code definition
- known as “DataBase Migration”
-
Evolution of DB: as app evolves - data model might change
- devs update code definition
- use migration tools to update db accordingly
# Connection String
.Api > appsettings.json
also make sure to add in .Api > program.cs: