CRUD using EF
Create & read data
Open Program.cs and replace the contents with the following code:
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
classin line 15 we added this object to our in-memory
DBSet
of studentsAdd is a method defined in DBSet class
in line 16 we called the
SaveChanges
method on our context objectin line 21 we queried the
DbSet
for a student object with ID onethe
Find
method is defined in theDBSet
class againentity 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 calleds
, again by entity frameworkonce 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