Updating and deleting objects

EF Core tracks objects' states through the ChangeTracker type. Every object that is retrieved from the database is automatically tracked by the ChangeTracker, and every change that is made on it changes the object's EntityState to Modified. If a retrieved object is removed from DbSet (or if an object that contains it is removed), EF Core will change the EntityState value to Deleted
When EF Core SaveChanges is executed, it scans the tracked objects, and if they are modified or deleted, EF Core generates an UPDATE statement with the relevant modifications that are needed, and a DELETE statement for the deleted objects. 
Here is a code snippet that shows how to update a product and then delete it:

var product = await _context.Products.FindAsync(id);
product.Title = "I've changed";
await _context.SaveChangesAsync(); // The entity is updated in the DB
_context.Products.Remove(product);
await _context.SaveChangesAsync(); // The entity is deleted from the DB
If you defined the relationships between your entities and enabled Cascade Delete (explicitly or implicitly), then when the principal object is removed from the DbSet, it will cause the dependent object to be removed as well. 

After data is stored in your database, it's natural that the next thing will be to create queries to retrieve it. Luckily, we don't need to learn SQL to query the data; instead, we can use the EF Core Querying API.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.37.10