Sub topic 1
What EF Core Is and Why Use an ORM
Most apps need to save data somewhere. Often that place is a relational database. A relational database is a program that stores data in tables made of rows and columns. Your C# code, however, works with objects and classes. This chapter explains how Entity Framework Core connects those two worlds.
The Gap Between Objects and Tables
In C#, you might describe a blog like this:
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; } = "";
}In a database, the same data lives in a table called Blogs, with a BlogId column and a Url column. Each row is one blog.
Without help, you must write SQL by hand to move data between them. SQL is the language databases understand. You would also need to copy each column into each property yourself:
SELECT BlogId, Url FROM Blogs WHERE Url LIKE '%example%';This works, but it is slow to write, easy to get wrong, and hard to change later.
What an ORM Does
An ORM (object-relational mapper) is a library that translates between objects and tables for you. You work with C# classes. The ORM writes the SQL, sends it to the database, and turns the results back into objects.
Entity Framework Core (EF Core) is Microsoft's ORM for .NET. It is free, open source, and works with many databases, such as SQLite, SQL Server, and PostgreSQL.
Here is a preview of the same query written with EF Core. You will build the db object in later chapters:
var blogs = await db.Blogs
.Where(b => b.Url.Contains("example"))
.ToListAsync();EF Core reads this LINQ query and creates the SQL for you. LINQ is the C# feature for querying data with methods like Where and OrderBy.
Why Use EF Core
| Benefit | What it means for you |
|---|---|
| Less code | No hand-written SQL for everyday tasks |
| Type safety | The compiler catches typos in property names |
| Change tracking | EF Core notices which objects you changed and saves only those |
| Migrations | Your database schema can grow along with your classes |
| Provider choice | You can switch databases with small changes |
Where EF Core Fits in an App
EF Core is the data access layer. It sits between your business logic and the database. Your web pages, APIs, or console apps call EF Core. They do not talk to the database directly. The main object you use is called a DbContext. You will meet it in an upcoming chapter.
Exercise
In one or two sentences, explain what problem an ORM like EF Core solves.
Show answer
Code works with objects, but a relational database stores rows in tables. An ORM translates between the two by generating SQL from your C# code and turning the results back into objects, so you don't write that mapping by hand.
Exercise
Name two benefits of using EF Core instead of writing all SQL by hand.
Show answer
Any two of these: less code to write, compile-time checking of property names, automatic change tracking, migrations for evolving the schema, and the ability to switch database providers easily.