find and solve ||
Please wait.....

CRUD Application In Core 3.1 || Entity Framework Code First

CRUD Application In Core 3.1 || Entity Framework Code First

CRUD Operation With ASP.NET Core MVC Using Visual Studio Code and Entity

CRUD Operations In ASP.NET Core Using Entity Framework Core Code First in C# · using System; · namespace CRUDApplication.Scaffold Your ASP.NET Core and Entity Framework Core Application. Install the Entity Framework Core Nuget Packages. Set up an Okta Application. Build your Entity Framework Core Application. Add Your Entity Framework Core Data Layer. Configure the Startup File. Add an Entity Framework Core Migration and Update. We will create a new web application using ASP.NET Core 2.2 and Angular with Entity Framework Core Code first approach. We will be creating a sample Staff Record Management system


⦁  Install .NET Core 2.2 or above SDK from'
⦁  Install the latest version of Visual Studio 2017 or 2019 from
⦁  SQL Server 2014/2016/2017  or above from  (Or you can download another site's free edition)

Installed Node.js and you can open the Node.js command prompt. And then command in the command prompt to install the Angular 8 CLI. First, you make sure the above are installed or not.

You can get the source code from Github. This repository has been updated to Angular 8 and ASP.NET Core 2.2.

Create MVC Web Application

Open Visual Studio 2017 and select File > New > Project.After selecting the project, a new project dialog will open on your computer given the below image. Select .NET Core  Web  Application inside the Visual C# menu from the left panel given. Then, select ASP.NET Core Web Application from the available project types list and then put the project's name as "FirstApp" and press OK.

Create MVC Web Application

After clicking on the OK button, a new dialog will open asking you to select the project template. There are two drop-down menus at the top left of the template window. Select “.NET Core” and “ASP.NET Core 2.2” from these dropdowns and select the “Angular” template and press the OK button.

 Add angular template in core

Now, our project will be created. You can see the folder structure in Solution Explorer as shown in the given below image.
the folder structure in Solution Explorer

The ClientApp folder is where the client side of our application resides. Inside the ClientApp/app/components folder.There are already have few components created which are provided by default with the Angular template in VS 2017. These components won’t affect our project, but we will delete fetch data and counter folders from our application folder path ClientApp/app/components folder. 

Adding the Model to the Application

We are using the Entity Framework core Code first approach to create our models. First, create New Folder under the project solution. Right-click on your project solution and select Add > New Folder. Name your folder  Entities 
Adding the Model to the Application

Right-click on the Entities folder and select Add > Class. Name your Connection Class  DbContext.cs and click Add button. And also add your entity model to the same folder[Entity model represents SQL Table]. At this point, the Entities folder will have the following structure.

Entities folder will have the following structure.
Open DBContext.cs and put the following code to handle Connection operations.  

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
namespace FirstApp.Entities {     public class DBContext : DbContext     {
        private IConfigurationRoot _config;
        public DBContext(IConfigurationRoot config, DbContextOptions options) : base(options)         {             _config = config;         }
        public DbSet<Staff> Staffs { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)         {             base.OnConfiguring(optionsBuilder);
            optionsBuilder.UseSqlServer(_config["ConnectionStrings:DefaultConnection"]);//connection string get by appsetting.json         }     } }

After that also Open Staff.cs and put the following code.   

using System;
using System.Collections.Generic;
using System. Linq;
using System.Threading.Tasks;
namespace FirstApp.Entities {     public class Staff     {         public string Id { get; set; }         public string FullName { get; set; }         public string Address { get; set; }         public string Gender { get; set; }     } }

Open appsettings.json and put the following code to handle the Connection string.

  Appsettings.json handle connection string in core. put the code in these appsettings. jsong to connect the client to the database server. like that.

  "ConnectionStrings": {
    "windowsAuthentication": true,
    "DefaultConnection": "Data Source=DESKTOP-9KQH8Q0;Database=FirstApp;Trusted_Connection=True;", //this is windows athenticaiton
    //"SqlAuthintication": "Server=DESKTOP-9KQH8Q0;Database=FirstApp;User ID=server;Password=server123;Trusted_Connection=True;Connection Timeout=30;"
    //"SqlAuthintication": "Server=DESKTOP-9KQH8Q0;Database=FirstApp;User ID=server;Password=server123;Trusted_Connection=True;Connection Timeout=30;"
  },   "Logging": {     "LogLevel": {       "Default": "Warning"     }   },   "AllowedHosts": "*" }  

Open Startup.cs and put the following code .

using FirstApp.Entities;

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SpaServices.AngularCli;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace FirstApp {     public class Startup     {         private IConfigurationRoot _config;         public Startup(IHostingEnvironment env)         {             var ConfigBuilder = new ConfigurationBuilder().SetBasePath(env.ContentRootPath)                         .AddJsonFile("appsettings.json");             _config = ConfigBuilder.Build();         }
        public IConfiguration Configuration { get; }
        // This method gets called by the runtime. Use this method to add services to the container.         public void ConfigureServices(IServiceCollection services)         {             services.AddSingleton(_config);             services.AddDbContext<DBContext>();             services.AddMvc();             services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            // In production, the Angular files will be served from this directory             services.AddSpaStaticFiles(configuration =>             {                 configuration.RootPath = "ClientApp/dist";             });         }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.         public void Configure(IApplicationBuilder app, IHostingEnvironment env)         {             if (env.IsDevelopment())             {                 app.UseDeveloperExceptionPage();             }             else             {                 app.UseExceptionHandler("/Error");                 // The default HSTS value is 30 days. You may want to change this for production scenarios, see                 app.UseHsts();             }
            app.UseHttpsRedirection();             app.UseStaticFiles();             app.UseSpaStaticFiles();
            app.UseMvc(routes =>             {                 routes.MapRoute(                     name: "default",                     template: "{controller}/{action=Index}/{id?}");             });
            app.UseSpa(spa =>             {                 // To learn more about options for serving an Angular SPA from ASP.NET Core,                 // see
                spa.Options.SourcePath = "ClientApp";
                if (env.IsDevelopment())                 {                     spa.UseAngularCliServer(npmScript: "start");                 }             });         }     } }  

After that, we are ready to Migration our project.EF Core migrations are a set of commands which you can execute in NuGet Package Manager Console or dotnet Command Line Interface (CLI).

More Details: is code first application so we are ready to migrate our First project.

Select View > other Windows >Package Manager Console given below. 

Package Manager Console

 After clicking Package Manager Console, At this point, the Package Manager Console will have the following structure. And Type "Add-Migration FirstMigration" as given below position. And Enter.

Add-Migration After Add-Migration FirstMigration, Show the result on the Package Manager Console given below. After Migration is successful then you must update your database  Update-Database like given below and then Enter.
Add-Migration  layout

See your SQL database, there is create database "FirstApp" and also create table "Staff".

Adding the Web API Controller to the Application

Right-click on the Controllers folder and select Add >> New Item.
An “Add New Item” dialog box will open. Select ASP.NET from the left panel, then select “Web API Controller Class” from the templates panel and put the name as StaffController.cs. Press OK.Adding the Web API Controller to the Application

 Open StaffController.cs file and put the following code into it. 

using System;
using System.Collections.Generic;
using System. Linq;
using System.Threading.Tasks;
using FirstApp.Entities;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling Web API for empty projects, visit
namespace FirstApp.Controllers {     [Route("api/[controller]")]     public class StaffController : Controller     {         private readonly DBContext _connection;         public StaffController(DBContext connection)         {             _connection = connection;         }         [HttpGet]         [Route("GetStaffList")]         public IActionResult GetStaffList()         {             var data = _connection.Staffs.ToList();             return Ok(data);         }     } }


Check result is fine or not in core 2.2. So I have Inserted the record manually into the SQL server. given below
Open SQL server select database FirstApp and run the script on this database

INSERT INTO Staffs (Id,FullName,Address,Gender) VALUES('1','Devin','Liotyo','Male')--insert statement in SQL server

 After running this SQL script on FirstApp Database, run your Asp.Net core project FirstApp.Output is given below.Api Response data display

We are done with our backend logic and core structure. So, we will now proceed to code our frontend using Angular.

Related information

Sundar  Neupane

Sundar Neupane

I like working on projects with a team that cares about creating beautiful and usable interfaces.

If felt valuable to you, feel free to share it.


Avatar for Ganesh   Khadka
Ganesh Khadka

I think this is perfect for me and another developer.Thank you so much sundar

Report Response