Modifying Data with EF Core: Insert Entities

Learn about inserting entities in EF Core, maintaining change tracking with DbContext, and calling SaveChanges to commit changes to the database.

We'll cover the following

Inserting, updating, and deleting entities using EF Core is an easy task to accomplish. DbContext maintains change tracking automatically so the local entities can track multiple changes, including adding new entities, modifying existing entities, and removing entities. Call the SaveChanges method when ready to send those changes to the underlying database. 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:

Step 1: Add a new class file named Program.Modifications.cs.

Step 2: In Program.Modifications.cs, create a partial Program class with a method named ListProducts that outputs the ID, name, cost, stock, and discontinued properties of each product sorted with the costliest first and highlights any that match an array of int values that can be optionally passed to the method, as shown in the following code:

Get hands-on with 1400+ tech skills courses.