Table of Contents (top down ↓)
Adding a Record
Open the solution explorer, and then the program.cs file. Scroll to the part where we left it in the previous tutorial.
Use the Add method of the Blogs DbSet to add a new record. The changes are committed by using the Save method of ProjectContext.
// completed program.cs file // Install-Package Microsoft.EntityFrameworkCore.Sqlite // Install-Package Microsoft.EntityFrameworkCore.Tools using ConsoleApp1.Models; using Microsoft.EntityFrameworkCore; // C# 8 using applies to the scope using var db = new ProjectContext(); if (db.Database.GetPendingMigrations().Any()) { db.Database.Migrate(); Console.WriteLine("All migrations applied!"); } if(!db.Database.CanConnect()) { Console.WriteLine("have you applied migration?"); Console.WriteLine("Open package manager console and"); Console.WriteLine("run this command first: "); Console.WriteLine("Add-Migration Initial_Create"); return; } // Create Console.WriteLine("Inserting a new blog"); db.Blogs.Add(new Blog { Heading = "My first blog" }); db.SaveChanges(); // query the blog entry var blog = db.Blogs.First(); // display it Console.WriteLine(blog); // modify the heading property blog.Heading = "New heading"; db.SaveChanges(); // query again blog = db.Blogs.First(); // display Console.WriteLine(blog); // delete db.Blogs.Remove(blog); db.SaveChanges(); // verify the count Console.WriteLine(db.Blogs.Count());
Video Explanation (see it happen!)
Please watch the following youtube video:
Reading the Record
We can read the record back by using any function such as First or FirstOrDefault.
The record is displayed to verify the contents.
Updating the Record
The Heading property can now be altered, and changes be saved to the database.
The record is again queried by using the First method. It is again displayed to verify that we get the changed data.
Deleting the Record
The record can be deleted by using the Remove method of the Blogs DbSet. After this the changes are saved.
// displayed output
Inserting a new blog
Blog { ID = 4, Heading = My first blog }
Blog { ID = 4, Heading = New heading }
0
Finally, we display the count of records in the database by using the Count extension method. We expect the display the number as zero.
Run the project to verify that everything is displayed as expected. The count of records is zero in the end. This is how CRUD operations can be done on a table with EF Core. Thanks!
This Blog Post/Article "(C# Language) EF Core - Complete CRUD Example Console Application" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.