Update & Delete
Updating entities
We can update the properties of entities by first fetching them and then modifying them and eventually saving them using the context
Replace the Program code with the one shown below
using EFGetStarted;
using System;
using System.Linq;
var db = new MyContext();
Console.WriteLine("List of students...\n");
foreach (var s in db.Students)
Console.WriteLine($" Id: {s.Id}\t Name: {s.Name} Is Enrolled: {s.IsEnrolled}");
Console.WriteLine();
Console.Write("Enter the ID of the student you wish to modify:");
var Id = int.Parse(Console.ReadLine());
var stud = db.Students.Find(Id);
if (stud is null)
Console.Write("Student not found!\n");
else
{
Console.Write("Enter new name:");
var name = Console.ReadLine();
stud.Name = name;
db.SaveChanges();
Console.WriteLine("List of students...\n");
foreach (var s in db.Students)
Console.WriteLine($" Id: {s.Id}\t Name: {s.Name} Is Enrolled: {s.IsEnrolled}");
}
Console.WriteLine("Press any key to exit");
Console.ReadKey();
Deleting entities
In order to delete entities, we take a similar approach except that we call Remove method on the DbSet
and then save the changes using the context
Replace the program code with the one shown below
using EFGetStarted;
using System;
using System.Linq;
var db = new MyContext();
Console.WriteLine("List of students...\n");
foreach (var s in db.Students)
Console.WriteLine($" Id: {s.Id}\t Name: {s.Name} Is Enrolled: {s.IsEnrolled}");
Console.WriteLine();
Console.Write("Enter the ID of the student you wish to delete:");
var Id = int.Parse(Console.ReadLine());
var stud = db.Students.Find(Id);
if (stud is null)
Console.Write("Student not found!\n");
else
{
db.Students.Remove(stud);
db.SaveChanges();
Console.WriteLine("List of students...\n");
foreach (var s in db.Students)
Console.WriteLine($" Id: {s.Id}\t Name: {s.Name} Is Enrolled: {s.IsEnrolled}");
}
Console.WriteLine("Press any key to exit");
Console.ReadKey();
Entity framework keeps tracking the changes to the entities and hence it knows what changes to perform on the underlying data store we can change this behavior and configure it otherwise, based on the situation! We will learn more about these in the upcoming sections.
Last updated