# Update & Delete

## Updating entities&#x20;

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&#x20;

```csharp
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();
```

{% hint style="info" %}
If the context object was not in _scope_, we need to take a different approach for modifying entities; like in the case of web applications where the state of the applications is not maintained between requests!
{% endhint %}

## Deleting entities&#x20;

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&#x20;

```csharp
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();
```

{% hint style="info" %}
We use a slightly different approach for deleting entities when the context is not in scope.
{% endhint %}

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.
