Entity Framework Core Basics
# CHAPTER 27
Entity Framework Core Basics
1. Introduction
In Chapter 25, we used ADO.NET. We wrote literal SQL strings ("SELECT * FROM Users") inside our C# code. This is error-prone, hard to maintain, and vulnerable to SQL injection.
Entity Framework Core (EF Core) is a modern Object-Relational Mapper (ORM). It allows you to interact with your database using 100% C# objects and LINQ. EF Core automatically translates your C# code into highly optimized, secure SQL commands behind the scenes.
2. Learning Objectives
By the end of this chapter, you will be able to:- Understand what an ORM is.
- Map a C# Class (Model) to a database table.
-
Create a
DbContextclass.
- Understand Code-First Migrations.
- Perform CRUD operations using C# and LINQ.
3. The Model (The Table Blueprint)
In EF Core, a database table is represented by a standard C# Class. The properties become the table columns.4. The DbContext (The Database Session)
TheDbContext is the bridge between your C# application and the database. It holds DbSet properties, which represent the actual tables.
5. Migrations (Creating the Database)
In the "Code-First" approach, you write the C# classes first, and EF Core generates the SQL database for you.In your terminal, you run:
-
1.
dotnet ef migrations add InitialCreate(Analyzes your C# classes and creates a blueprint).
-
2.
dotnet ef database update(Executes the blueprint, actually creating the database file/tables).
6. Performing CRUD Operations
Once the database exists, you interact with it using standard C# syntax. No SQL strings required!7. Why use EF Core over ADO.NET?
-
Type Safety: If you rename a property from
PricetoCost, the C# compiler ensures all your queries update. With raw SQL strings, you wouldn't know it was broken until runtime.
- Security: EF Core automatically uses parameterized queries, making SQL injection impossible.
-
Productivity: Writing
.Add()and.SaveChanges()takes 2 seconds. Writing standard SQL insert logic in ADO.NET takes 15 lines of code.
8. Common Mistakes
-
Forgetting
.SaveChanges(): You can.Add()100 items to the DbSet, but absolutely nothing happens in the actual database until you explicitly calldb.SaveChanges().
-
Querying inside a loop (N+1 Problem): Running a LINQ query to the database inside a
foreachloop will execute hundreds of separate SQL commands, crashing server performance. Fetch the data once into aList, then loop.
9. Best Practices
-
Use EF Core's Asynchronous methods (
SaveChangesAsync,ToListAsync) in web applications to prevent freezing the server threads during database I/O.
10. Exercises
-
1.
Define a
Studentclass withId,Name, andGradeproperties.
-
2.
Create a
SchoolContextclass inheriting fromDbContextcontaining aDbSet<Student> Students.
11. MCQs with Answers
What does ORM stand for?
Q3. In the EF Core "Code-First" approach, what determines the database schema? a) The SQL Server Administrator b) Your C# Models (Classes) c) An XML file Answer: b) Your C# Models (Classes)
Which EF Core class acts as the main bridge/session between your code and the database?
Inside the DbContext, what property type represents a database table?
What happens if a C# Model has a property named Id?
What feature analyzes your C# models and generates the commands to update the SQL database structure?
What command actually sends your changes (Inserts, Updates, Deletes) to the database?
Which technology does EF Core use to query the database using C# syntax?
How does EF Core handle SQL Injection?
12. Interview Questions
- Q: Explain the Code-First vs Database-First approach in EF Core.
-
Q: What is the N+1 Query Problem in Entity Framework, and how do you solve it using
.Include()(Eager Loading)?
-
Q: Explain the role of the
DbContext.
13. Summary
Entity Framework Core bridges the gap between Object-Oriented C# and Relational SQL Databases. By mapping classes to tables (DbSet), using Migrations to create schemas, and leveraging LINQ for queries, EF Core massively increases developer productivity and security.