Modifying data with EF Core
Inserting, updating, and deleting entities using EF Core is an easy task to accomplish. This is often referred to as CRUD, an acronym that includes the following operations:
- C for Create
- R for Retrieve (or Read)
- U for Update
- D for Delete
By default, DbContext
maintains change tracking automatically, so the local entities can have multiple changes tracked, including adding new entities, modifying existing entities, and removing entities.When you are ready to send those changes to the underlying database, call the SaveChanges
method. The number of entities successfully changed will be returned.
Inserting entities
Let's start by looking at how to add a new row to a table:
- In the
WorkingWithEFCore
project, add a new class file namedProgram.Modifications.cs
. - In
Program.Modifications.cs
, create a partialProgram
class with a method namedListProducts
that outputs the ID, name, cost, stock, and discontinued properties of each product, sorted with the costliest...