Sub topic 1
What EF Core Is and Why Use an ORM
Most apps need to save data somewhere. A shopping site saves orders. A blog saves posts. Often that data goes into a relational database. A relational database is a program that stores data in tables made of rows and columns.
Your C# code works with objects, while the database works with tables. This chapter explains how a tool called an ORM connects the two. It also explains where Entity Framework Core (EF Core) fits in a .NET app.
You do not need to write any database code yet. The goal here is to understand the idea. The next chapters build a real project step by step.
Two Different Worlds
C# code thinks in objects. An object is a bundle of data and behavior made from a class. A Blog object might have a Url property and a list of Post objects.
A database thinks in tables. A table is a grid. Each row is one record, and each column is one piece of data, such as a URL. Tables link to each other with keys. A primary key is a column that uniquely identifies each row. A foreign key is a column that points to a row in another table.
Here is the same idea in both worlds. First, a C# class:
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; } = "";
}Now a matching database table, written in SQL. SQL (Structured Query Language) is the language databases understand.
CREATE TABLE Blogs (
BlogId INTEGER PRIMARY KEY,
Url TEXT NOT NULL
);
INSERT INTO Blogs (Url) VALUES ('https://example.com/blog');
SELECT BlogId, Url FROM Blogs WHERE Url LIKE '%example%';The two shapes look alike, but they are not the same. Someone has to move data between them. Without help, that someone is you.
The Hard Way: Mapping by Hand
Without an ORM, your code must do these jobs itself:
- Open a connection to the database.
- Write SQL as text strings.
- Send the SQL and read back the rows.
- Copy each column into a property on a new object.
- Track which objects you changed.
- Write more SQL to save those changes.
This works, but it is slow to write and easy to get wrong. A typo inside a SQL string does not show up when you compile. You find out only when the program runs. If you rename a property in C#, nothing warns you that the SQL still uses the old name.
What an ORM Does
An ORM (object-relational mapper) is a library that does this mapping for you. "Object" means your C# classes. "Relational" means the database tables. "Mapper" means it connects one to the other.
With an ORM, you mostly work with plain C# objects. The ORM handles the rest:
| Job | Without an ORM | With an ORM |
|---|---|---|
| Read data | Write a SELECT string, copy columns into objects | Write a C# query and get objects back |
| Save new data | Write an INSERT string with parameters | Add an object and call save |
| Change data | Write an UPDATE string, track what changed | Change a property and call save |
| Build tables | Write CREATE TABLE scripts by hand | Generate them from your classes |
| Catch mistakes | Mostly when the program runs | Many at compile time |
Where EF Core Fits
EF Core is Microsoft's ORM for .NET. It is free and open source. It runs on Windows, macOS, and Linux.
EF Core has a few main parts. You will meet each one in later chapters:
- Entity classes are your normal C# classes, like
Blog. Each one usually maps to a table. - DbContext is a class that represents a working session with the database. You ask it for data, and you tell it to save.
- A provider is a plug-in package that teaches EF Core how to talk to one kind of database. There are providers for SQLite, SQL Server, PostgreSQL, MySQL, and others.
- Migrations are generated files that create and update the database tables to match your classes.
This diagram shows how a request travels from your code to the database and back.
LINQ: One Query Style for Lists and Databases
LINQ (Language Integrated Query) is a C# feature for querying data. You may already use it on lists. The program below runs on its own. It uses LINQ on a normal list in memory.
var blogs = new List<Blog>
{
new Blog { BlogId = 1, Url = "https://example.com/blog" },
new Blog { BlogId = 2, Url = "https://other.net/news" }
};
var matches = blogs
.Where(b => b.Url.Contains("example"))
.OrderBy(b => b.BlogId)
.ToList();
foreach (var blog in matches)
{
Console.WriteLine($"{blog.BlogId}: {blog.Url}");
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; } = "";
}To try it, create a project with dotnet new console, paste this into Program.cs, and run dotnet run. It prints 1: https://example.com/blog.
EF Core lets you write almost the same query against a database. The difference is that EF Core does not loop over a list. It translates your LINQ into SQL, much like the SELECT statement shown earlier. Then the database does the filtering and sorting.
Why Use an ORM
The main benefits for beginners are:
- Less repeated code. You skip the copy-columns-into-objects work.
- Safer queries. EF Core sends values as parameters. A parameter is a value sent apart from the SQL text, which blocks a common attack called SQL injection.
- Easier changes. Migrations keep the database in step with your classes.
- Switchable databases. Changing providers often takes only a small code change, though each database has its own limits.
When to Be Careful
An ORM is a helper. It does not replace knowing how databases work. Keep these limits in mind:
- EF Core writes the SQL for you, and sometimes that SQL is slow. Later chapters show how to see the generated SQL.
- Very complex reports can be easier to write in raw SQL. EF Core still lets you run SQL directly when you need to.
- You still need to understand tables, keys, and indexes to design a good model.
Key Terms
| Term | Meaning |
|---|---|
| Relational database | A program that stores data in linked tables |
| SQL | The language used to query and change a database |
| ORM | A library that maps objects to tables and back |
| Entity | A C# class whose objects are stored in a table |
| DbContext | The EF Core class you use to query and save data |
| Provider | A package that connects EF Core to one database type |
| LINQ | C# syntax for writing queries |
Exercises
Exercise
In your own words, what are the two "worlds" an ORM connects, and what does each one use to store data?
Show answer
An ORM connects C# code and a relational database. C# code stores data in objects made from classes. The database stores data in tables made of rows and columns. The ORM moves data between objects and tables so you don't have to copy it by hand.
Exercise
You want EF Core to work with a PostgreSQL database instead of SQLite. Which EF Core part do you need to change?
Show answer
The database provider. A provider is the package that teaches EF Core how to talk to one kind of database, so you would swap the SQLite provider for a PostgreSQL provider and update the connection settings.
Exercise
Give one reason a typo is caught sooner in a LINQ query than in a SQL string.
Show answer
A LINQ query is C# code, so the compiler checks property names when you build. A SQL string is just text to the compiler, so a misspelled column name shows up only when the program runs and the database rejects the query.
Exercise
Name one situation where you might still write raw SQL even though you use EF Core.
Show answer
Two examples: a very complex report query that is hard to express in LINQ, or a query where the SQL that EF Core generates is too slow and you need hand-tuned SQL.