Entity Framework Core SaveChanges | Save Data

In this entity framework core tutorial will discuss to save data using entity framework core savechanges method and it will includes insert, update and delete operations.

Entity Framework Core provides different ways to add, update, or delete data in the database for that we need to use entity framework core savechanges method. An entity contains data in its scalar property will be either inserted or updated or deleted based on its EntityState.

Step 1: Create interface ‘IStudentContract.cs’.

public interface IStudentContract
{
   Student GetStudent(int id);
   List GetAllStudent();
   List GetAllStudentByName(string name);
   void Add(Student student);
   void Update(Student student);
   void Delete(int studentID);
}

Step 2: Create service ‘StudentService.cs’ which impments the above contract.

public class StudentService : IStudentContract
{
   public List GetAllStudent()
   {
     var context = new SchoolContext();
     List students = context.Student.Include(c => c.StudentAddress).AsNoTracking().ToList();
     return students;
   }

   public List GetAllStudentByName(string name)
   {
     var context = new SchoolContext();
     List students = context.Student.Where(c => c.Name.Equals(name)).ToList();
     return students;
   }

   public Student GetStudent(int id)
   {
      var context = new SchoolContext();
      Student student = context.Student.Where(c => c.ID == id).FirstOrDefault();
     return student;
   }

   public void Add(Student student)
   {
     throw new NotImplementedException();
   }
   
   public void Update(Student student)
   {
     throw new NotImplementedException();
   }

   public void Delete(int studentID)
   {
     throw new NotImplementedException();
   }
}

In our previous tutorial we have seen how to query to entity framework code and fetch data as per our requirement. In this tutorial will see how to saving.

Adding or Inserting data

To add data to the database, you can use the DbSet.Add method to add new instances of your entity classes, and then call SaveChanges().

public void Add(Student student)
{
   using (var context = new SchoolContext())
   {
      context.Student.Add(student);
      context.SaveChanges();
   }
}

In the above example, context.Student.Add(student) adds a newly created instance of the Student entity to a context with Added EntityState.After this, the SaveChanges() method builds and executes the following INSERT statement to the database.

Updating or Modifying data

When we make changes to any existing entity, or simply modify the values assigned to properties and then call SaveChanges(), it will update the data into a database.

EF Core API keeps track of all the entities retrieved using a context. So, when you update entity data, EF automatically marks EntityState to Modified, which results in an updated statement in the database when you call the SaveChanges() method.

public void Update(Student student)
{
   using (var context = new SchoolContext())
   {
      var studentObj = context.Student.Where(c => c.ID == student.ID).FirstOrDefault();
      studentObj.Name = student.Name;
      context.SaveChanges();
    }
}

In the above example, we have get the student record  from the database using the pass entity student id. We modify the Name of the, so in this case the context sets its EntityState to Modified because of the modification performed in the scope of the DbContext instance (context). So, when we call the entity framework core savechanges  method, it builds and executes the Update statement in the database.

Deleting or Removing Data

We can use the DbSet.Remove() method to delete instances of your entity classes. below are some important points.

      • If the entity already exists in the database, it will be deleted during SaveChanges().
      • If the entity has not yet been saved to the database, then it will be removed from the context and will no longer be inserted when SaveChanges() is called.
public void Delete(int studentID)
{
   using (var context = new SchoolContext())
  {
    var student = context.Student.Where(c => c.ID == studentID).FirstOrDefault();
    context.Student.Remove(student);
    context.SaveChanges();
  }
}

Basically the entity framework core savechanges  method  is use to perform all saving operations. After making all changes in student service. we have below service fully read to perform the get and post operations.

public class StudentService : IStudentContract
{
public void Add(Student student)
{
using (var context = new SchoolContext())
{
context.Student.Add(student);
context.SaveChanges();
}
}
public void Delete(int studentID)
{
using (var context = new SchoolContext())
{
var student = context.Student.Where(c => c.ID == studentID).FirstOrDefault();
context.Student.Remove(student);
context.SaveChanges();
}
}
public List GetAllStudent()
{
var context = new SchoolContext();
List students = context.Student.Include(c => c.StudentAddress).AsNoTracking().ToList();
return students;
}

You can watch our video version of this tutorial with step by step explanation.