Manipulating data with EF Core
It is easy to insert, update, and delete entities using EF Core.
Inserting entities
At the bottom of the Main
method, after the foreach
statement, add the following code to insert a new product and relist all products:
var newProduct = new Product { CategoryID = 6, // Meat & Poultry ProductName = "Bob's Burger", UnitPrice = 500M }; // mark product as added in change tracking db.Products.Add(newProduct); // save tracked changes to database db.SaveChanges(); foreach (var item in db.Products) { WriteLine($"{item.ProductID}: {item.ProductName} costs {item.UnitPrice:$#,##0.00}"); }
Rerun the application and enter 50
. You will see that the product has been inserted:
78: Bob's Burger costs $500.00
Updating entities
Add the ...
Get C# 7 and .NET Core: Modern Cross-Platform Development - Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.