find and solve || findandsolve.com
Please wait.....

CRUD Application In asp.net Core 3.1 || Entity Framework Code First

CRUD Application In asp.net 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 · 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 are going to create an 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

Prerequisites

⦁  Install .NET Core 2.2 or above SDK from https://dotnet.microsoft.com/learn/dotnet/hello-world-tutorial/intro#windowscmd'
⦁  Install the latest version of Visual Studio 2017 or 2019 from https://visualstudio.microsoft.com/downloads/
⦁  SQL Server 2014/2016/2017  or above from https://www.microsoft.com/en-us/sql-server/sql-server-editions-express  (Or you can download antoher sites 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 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 in your computer given below image.Select .NET Core  Web  Application inside Visual C# menu from the left panel given.Then,select ASP.NET Core Web Application from available project types list and then Put the name of the project as "FirstApp" and press OK.

Create MVC Web Application

After clicking on 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 “Angular” template and press OK Button.

 Add angular template in asp.net 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 where the client side of our application resides. Inside the ClientApp/app/components folder.There is 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 fetchdata and counter folders from our application folder path ClientApp/app/components folder. 

Adding the Model to the Application

We are using Entity Framework core Code first approach to create our models.First create New Folder under 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 Entities folder and select Add > Class. Name your Connection Class  DbContext.cs and click Add button. And also add your entity model  as same folder[Entity model is represent sql Table]. At this point of time, 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 Connection string.

  Appsettings.json handle connection string in asp.net core.put the code in this appsettings.jsong to connect client to 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 https://aka.ms/aspnetcore-hsts.                 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 https://go.microsoft.com/fwlink/?linkid=864501
                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 in dotnet Command Line Interface (CLI).
 

More Details :https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/?tabs=dotnet-core-cli.This is code first application so we are ready to migration our First project.

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

Package Manager Console

 After click Package Manager Console,At this point of time, 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 Package Manager Console given below.After Migration is success then you must update your database  Update-Database like given below and then Enter.
Add-Migration  layout

See your sql databse,there is create databse "FirstApp" and also create table "Staff".
 

Adding the Web API Controller to the Application
 

Right click on 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 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 https://go.microsoft.com/fwlink/?LinkID=397860
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);         }     } }

 NOTE:

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

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

 After Run this sql script on FirstApp Databse then run your Asp.Net core project FirstApp.Output is given below.Api Response data display

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

Sundar  Neupane

Sundar Neupane

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

1 Comments


Avatar for Ganesh   Khadka
Ganesh Khadka

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


Report Response