05 - Entity Framework Intro
EF Core
Entity Framework (EF) Core is a lightweight, extensible, open source and cross-platform version of the popular Entity Framework (EF 6) data access technology.
EF Core can serve as an object-relational mapper (O/RM), which:
- Enables .NET developers to work with a database using .NET objects.
- Eliminates the need for most of the data-access code that typically needs to be written.
EF Core supports many database engines: MS SQL, MariaDb, Postgresql, SQLite,...
Tooling
Install
1 |
|
or update
1 |
|
Add nuget packages as needed:
- Microsoft.EntityFrameworkCore.Design
- Microsoft.EntityFrameworkCore.Sqlite
- Microsoft.EntityFrameworkCore.SqlServer
- Microsoft.EntityFrameworkCore.Tools
Model
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
1 2 3 4 5 6 7 8 9 |
|
Context
The context object allows querying and saving data.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
When using SQLite – specify full path to db location.
1 |
|
Basics
Steps to follow
- Write your models (POCO-s)
- Every class used in EF needs primary key (PK)
- By convention, PK-s are named
<ClassName>Id
orId
- Declare context class, derived from DbContext
- Inside context class add
DbSet<YourPoco>
- If you don’t include all pocos in DbSets, EF will autodiscover them and create tables for them
- Don’t rely on EF automatic creation of properties, relations, or any other configuration! Check your DB structure, does it match your model 1:1?
Initial migration
EF Core will not automatically create for you db creation code
From command line in solution folder
Create new migration
1 |
|
Update DB
1 |
|
Delete DB
1 |
|
Migrations folder is created, with necessary classes for DB creation and Model structure
Verify DB Structure
- Check DB structure you got!
- It should match your model 1:1
- Look out for automatically created fields or tables
- Use VS View->Server Explorer or MS SQL Server Management Studio
- Or any other tool suitable for your DB engine
- EF Core supports several DB engines (most have multiple connector providers)
Use your model/context
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
Food for thought
Intermediate-level knowledge or higher of the underlying database server is essential to architect, debug, profile, and migrate data in high performance production apps. For example, knowledge of primary and foreign keys, constraints, indexes, normalization, DML (Data Manipulation Language) and DDL (Data Definition Language) statements, data types, profiling, etc.