CRUD using EF
Last updated
Last updated
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();
If you do not see the entries as shown below, make sure you refresh the SQL server using the blue refresh circular arrow
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
You can also try creating and reading more student objects as shown above.
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