Learn how to delete records from the database using Entity Framework Core. Deleting an entity is done using the Remove or RemoveRange method of the DbSet. Alternatively, you can also set the entity state as Deleted. We can delete records either in connected or disconnected Scenarios. We will also look at how to remove multiple records from the database using the RemoveRange method.
Entity Framework Core
Learn how an entity framework core update records to the database. We can update records either in connected or disconnected scenarios. In the connected Scenario, we open the context, query for the entity, edit it, and call the SaveChanges method. In the Disconnected scenario, we need to is to attach/add it to the context. Set its State as Modified and then call the SaveChanges But we need to be careful in a disconnected scenario as the update will update all the fields, There is a chance of accidentally overwriting a field. We also show you how to update multiple records & Related Data etc.
In this tutorial let us look at how to add a record, add multiple records to the database. Before inserting records into the database, we must add the entities to the context first. To do that we use the Add & AddRange methods. Once the records are added to the context, we can call the SaveChanges method, which sends the insert query to the database. The EF Core also takes care of updating identity values generated in the database in the entity. We also show you how to add related entities or data.
Entity Framework Core SaveChanges method of DbContext class handles the persisting of data to the database. When we use the SaveChanges it prepares the corresponding insert, update, delete queries. It then wraps them in a Transaction and sends it to the database. If any of the queries fails all the statements are rolled back. The Context also manages the entity objects during run time, which includes populating objects with data from a database, change tracking, etc.
The ChangeTracker in EF Core tracks changes made to every entity by assigning them the Entity States. It uses the EntityEntry class to store the tracking information of a given entity. The Entity States represents the state of an entity. The Entity State can be Added, Deleted, Modified, Unchanged or Detached. For example, when we add a new entity to DbContext using the Add / AddRange method, the DbContext sets the state of the entity as Added. When we query and load the entity the state is set to Unchanged. If we make any changes to the entity then its state becomes Modified The SaveChanges uses these states to determine to generate the SQL query ( Insert,Update or Delete )