Manipulating data with EF Core
Inserting, updating, and deleting entities using EF Core is an easy task to accomplish.
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
Program.cs
, create a new method namedAddProduct
, as shown in the following code:static bool AddProduct( int categoryId, string productName, decimal? price) { using (Northwind db = new()) { Product p = new() { CategoryId = categoryId, ProductName = productName, Cost = price }; // mark product as added in change tracking db.Products.Add(p); // save tracked change...