Updated February 14, 2023
Introduction to Entity Framework SaveChanges
Entity Framework SaveChanges saves the fundamental changes made in the database context. The SaveChanges method can add, modify, and delete data using the context and entity classes. In addition, this SaveChanges method habitually calls the DeleteChanges() method to discover the entity instances’ changes before saving the primary database.
Overview of Entity Framework SaveChanges
The Overview of Entity Framework SaveChanges() method stores the entire changes made in the database context. In Entity Framework, the method SaveChanges() develops the transaction and binds all the operations like insert, update and delete. To multiple SaveChanges() calls to build the transactions, perform the CRUD Operations, and commit the transaction.
In Entity Framework Version 4, there is an option to override the default SaveChanges() method to use some business logic or custom code before performing the changes in the database. This feature is easy to use when having the entity with properties used commonly, which is required to execute automatically. There are a few circumstances in which the entities we modified date and that particular modified by user property needed to be updated correctly every time for the entire application.
Instead of allocating values to the property every time for the entire application, we need to perform at a single place with several logic for those entities to populate the modified data and user name; then, we can store the changes in the database. This circumstance is called the overriding SaveChanges() method of Entity Framework.
Entity Framework SaveChanges Methods
The Entity Framework SaveChanges() method of DbContext saves the modifications made to the entities in the database. Let’s see the following example, which explains adding, removing, and modifying data using the SaveChanges method.
Several SaveChanges methods are as follows:
1. Add Record
This method creates the new entity and adds the method to the entity context. To call the SaveChanges to endure the data to the database.
Code:
using (var dbContext = new BookStore())
{
AuthorMaster authorObj = new AuthorMaster()
{
Author_FirstName = "Peter",
Author_LastName = "Paul",
};
dbContext.Authors.Add(authorObj);
dbContext.SaveChanges();
}
2. Update Record
This method is used for querying and gets the entity to which the data is required to modify, to make the essential changes, and finally, to make a call to SaveChanges.
Code:
using (var dbContext = new BookStore())
{
var get_author = context.Authors
.FirstOrDefault();
get_author.Author_LastName = "Rio";
dbContext.SaveChanges();
}
3. Delete Record
This method removes the entity for deletion. It deletes the instance of entity classes by use of DbSet.Remove.
- To check whether the entity already exists in the database, it automatically deletes the data during the SaveChanges.
- If the entity has not been saved to the database when it is removed from the database context, it will no longer be inserted when DaveChanges is called.
Code:
using (var dbContext = new BookStore())
{
var get_author = context.Authors
.Where(s => s.AuthorId == 3)
.FirstOrDefault();
dbContext.Authors.Remove(get_author);
dbContext.SaveChanges();
}
Entity Framework SaveChanges Database
Entity Framework SaveChanges stores the entire changes made in the database context. The SaveChanges method adds, modifies, and deletes data using the context and entity classes. Let’s see the Entity Framework saveChanges Database process contains the connected and disconnected scenario.
The Entity Framework SaveChanges method of DbContext organizes the Delete, Insert and Update Queries. It also performs to track the modifications of each entity. While we are querying the database for entities, the context gets them and spots the entity as unchanged. The DbContext keeps track of the entities by the property ChangeTracker. At any time we add, delete or update the entities, it spots them as Added, Deleted, or Updated. Whenever we call the SaveChanges method, it loops through the entities and checks and tracks for their states.
It prepares for inserting, deleting, or updating SQL Statements and wraps them inside a single transaction before sending them to the database. It would roll back fundamental changes if any statements failed to proceed. For SaveChanges, the context will work accurately to mark the entity as added, deleted, or updated. In case of closing the context and making the modifications to the entity, which the context will not track, we use two possibilities.
- Connected Scenario
- Disconnected Scenario
1. Connected Scenario
In the Connected Scenario, we do not need to close the context throughout the lifetime of the entities. The ChangeTracker will keep track of the changes made at entities; if the context is in an open state, it knows which entity is modified/ added, or deleted. The context will create the exact SQL queries (insert, delete or update) during the SaveChanges method call depending on the entity’s state (added, deleted, or modified).
Let’s see the code below explaining the SaveChanges in the Connected Scenario. Initially, we generate the context by using a statement and then get the Department entity from the database and alter the property Description of the entity. We then include a new entity to update and delete an entity. At last, to make a call on the SaveChanges method to endure data back to the database. The whole process occurs in the same context. We do not need to close or delete the context while storing and retrieving the entities.
Code:
using (dbContext db = new dbContext())
{
var dept = db.Departments.Where(d => d.Name == "Designing").First();
dept.Description = "Graphical Designing Departmet";
db.SaveChanges();
}
2. Disconnected scenario
In real-life applications, the Connected Scenario is not always applicable. Let’s see one example; take the Web Application the user requests for the Department entity. Here we generate a new instance to fetch the data and sending back to the user. The Server closes the context and disposes of it. Currently, the user updates the department entity and returns and creates a new context instance. The new instances do not know about the Department entity; it doesn’t know whether it’s a newly created or existing entity.
Code:
{
Department deptObj;
using (dbContext db = new dbContext())
{
deptObj = db.Departments.Where(d => d.Name == "Networking").First();
}
//here the Context is Closed
deptObj.Description = "Disconnected Scenario - Networking Department";
//here to creating new context
using (dbContext db = new dbContext())
{
db.Entry(deptObj).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
}
}
Conclusion
In this article, we have seen the Entity Framework SaveChanges, which saves the entire modifications made in the database context.
Recommended Articles
This is a guide to Entity Framework SaveChanges. Here we discuss the introduction, entity framework SaveChanges methods, and database. You may also have a look at the following articles to learn more –