CRUD using EF

Create & read data

Open Program.cs and replace the contents with the following code:

using EFGetStarted;
using System;
using System.Linq;

var db = new MyContext();

Console.WriteLine("Creating a student");

var student = new Student()
{
    Name = "Raj",
    IsEnrolled = true
};

db.Students.Add(student);
db.SaveChanges();
Console.WriteLine("Done!");

Console.WriteLine("Here is the student with ID 1:");

var s = db.Students.Find(1);

Console.WriteLine(s.Name);

Console.WriteLine("Press any key to exit");
Console.ReadKey();

We must not provide explicit values for Id property of the student object as the database will create them automatically. Doing so will throw an error!

Database entry created

If you do not see the entries as shown below, make sure you refresh the SQL server using the blue refresh circular arrow

So how did we read and write the database?

We just performed our first read and write operations to the database using entity framework core, but how did we do this?

  • In line number 5 we instantiated an object of MyContext class

  • in line 15 we added this object to our in-memory DBSet of students

    • Add is a method defined in DBSet class

  • in line 16 we called the SaveChanges method on our context object

  • in line 21 we queried the DbSet for a student object with ID one

    • the Find method is defined in the DBSet class again

    • entity framework issues the respective SQL query to the underlying database which in our case is an SQL Server

    • the result from the database is mapped to a Student object called s, again by entity framework

    • once we have the object (and its values) in memory, we can print any information about it like we have done in line 23

No changes are persisted to the underlying database until we call the SaveChanges method on the context object like we have done online 16.

We can also have more than one change pending to be reflected on the database all of which will be executed on the database once the SaveChanges is called.

You can also try creating and reading more student objects as shown above.

Last updated