Wednesday, 14 December 2016

EF Basic 21:CRUD Operation

CRUD Operation in Connected Scenario

CRUD operation in connected scenario is a fairly easy task because the context automatically tracks the changes that happened in the entity during its lifetime, provided AutoDetectChangesEnabled is true, by default.
Make sure that you have created an Entity Data Model as shown in the Create Entity Data Modelsection for SchoolDB sample database.
The following example shows how you can add, update, and delete an entity in the connected scenario (within the scope of context), which in turn will execute insert, update, and delete commands on the database. Context will automatically detect the changes and update the state of an entity.
using (var context = new SchoolDBEntities())
{
    var studentList = context.Students.ToList<Student>();

    //Perform create operation
    context.Students.Add(new Student() { StudentName = "New Student" });

    //Perform Update operation
    Student studentToUpdate = studentList.Where(s => s.StudentName == "student1").FirstOrDefault<Student>();
    studentToUpdate.StudentName = "Edited student1";

    //Perform delete operation
    context.Students.Remove(studentList.ElementAt<Student>(0));

    //Execute Inser, Update & Delete queries in the database
    context.SaveChanges();
} 
Note: If context.Configuration.AutoDetectChangesEnabled = false then context cannot detect changes made to existing entities so do not execute update query. You need to call context.ChangeTracker.DetectChanges() before SaveChanges() in order to detect the edited entities and mark their status as Modified.
Context detects adding and deleting entity, when the operation is performed only on DbSet. If you perform add and delete entity on a separate collection or list, then it won't detect these changes.
The following code will NOT insert or delete student. It will only update the student entity because we are adding and deleting entities from the List and not from DbSet.
using (var context = new SchoolDBEntities())
{
    var studentList = context.Students.ToList<Student>();

    //Add student in list
    studentList.Add(new Student() { StudentName = "New Student" });

    //Perform update operation
    Student studentToUpdate = studentList.Where(s => s.StudentName == "Student1").FirstOrDefault<Student>();
    studentToUpdate.StudentName = "Edited student1";

    //Delete student from list
    if (studentList.Count > 0)
        studentList.Remove(studentList.ElementAt<Student>(0));

    //SaveChanges will only do update operation not add and delete
    context.SaveChanges();
}
Learn how to do the CRUD operation in the disconnected scenario in the next sections.

No comments:

Post a Comment