التخطي إلى المحتوى الرئيسي

How to perform CRUD Operation in .NET CORE using Database First Approach:- BY Shiva Sir

 How to perform CRUD Operation in .NET CORE using Database First Approach:-  BY Shiva Sir:-

Database First means you should create database and table from Database end and Program Code and Business Logic from application end.


Database first most useful approach in Entity framework for large projects.


1)  Create Database 


2)  Create Table


3)  Create .NET MVC Project


4)  MICROSOFT.ENTITYFRAMEWORKCORE.SqlServer


MICROSOFT.ENTITYFRAMEWORKCORE.TOOLS


MICROSOFT.ENTITYFRAMEWORK.CORE


5)  WRITE THIS COMMAND to GENERATE CONTEXT CLASS AND MODEL CLASS.


Scaffold-DbContext "Data Source=(localdb)\ProjectsV13;Initial Catalog=Northwind;

Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;" 

-Provider Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models/DB


6)  go into appsetting.json file and create connection String


{

  "Logging": {

    "LogLevel": {

      "Default": "Information",

      "Microsoft.AspNetCore": "Warning"

    }

  },

  "AllowedHosts": "*",

  "ConnectionStrings": {

    "WinAuth": "Data Source=SHIVA-PC\\SQLEXPRESS;Initial Catalog=collegeerp;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;"

    

  }

}


7)  Configure Connection String in Program.cs file


builder.Services.AddDbContext<CollegeerpContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("WinAuth")));


8)  Right Click on Contoller and add Scaffold Controller and choose Read write Entity framework then select context and model class it will automatically generate complete code of an application for CRUD Operation.


..........................................................................................................................................................


Important Code SNIPPET:-

Code of  CollegeErpContext.cs file


using System;

using System.Collections.Generic;

using Microsoft.EntityFrameworkCore;


namespace entityframeworkexample.Models.DB;


public partial class CollegeerpContext : DbContext

{

    public CollegeerpContext()

    {

    }


    public CollegeerpContext(DbContextOptions<CollegeerpContext> options)

        : base(options)

    {

    }


    public virtual DbSet<Student> Students { get; set; }


    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)

    {

        

    }


    protected override void OnModelCreating(ModelBuilder modelBuilder)

    {

        modelBuilder.Entity<Student>(entity =>

        {

            entity.HasKey(e => e.Rno).HasName("PK_tbl_student");


            entity.ToTable("Student");


            entity.Property(e => e.Rno)

                .ValueGeneratedNever()

                .HasColumnName("rno");

            entity.Property(e => e.Branch)

                .HasMaxLength(50)

                .IsUnicode(false)

                .HasColumnName("branch");

            entity.Property(e => e.Fees).HasColumnName("fees");

            entity.Property(e => e.Sname)

                .HasMaxLength(50)

                .IsUnicode(false)

                .HasColumnName("sname");

        });


       // OnModelCreatingPartial(modelBuilder);

    }


   // partial void OnModelCreatingPartial(ModelBuilder modelBuilder);

}



Code of Model Class:-


using System;

using System.Collections.Generic;


namespace entityframeworkexample.Models.DB;


public partial class Student

{

    public int Rno { get; set; }


    public string? Sname { get; set; }


    public string? Branch { get; set; }


    public int? Fees { get; set; }

}

.............................................................................

Code of AppSettings.Json File:-

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "WinAuth": "Data Source=SHIVA-PC\\SQLEXPRESS;Initial Catalog=collegeerp;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;"
    
  }
}



Code of Program.cs

using Microsoft.EntityFrameworkCore;
using System.Data.Common;
using entityframeworkexample.Models;
using entityframeworkexample.Models.DB;

namespace entityframeworkexample
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.
            builder.Services.AddControllersWithViews();
            builder.Services.AddDbContext<CollegeerpContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("WinAuth")));
            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Home/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.UseRouting();

            app.UseAuthorization();

            app.MapControllerRoute(
                name: "default",
                pattern: "{controller=Students}/{action=Index}/{id?}");

            app.Run();
        }
    }
}




HOW to CREATE CUSTOM CODE FOR CRUD OPERATION in .NET CORE MVC:-



using entityframeworkexample.Models.DB;

using Microsoft.AspNetCore.Mvc;

using Microsoft.EntityFrameworkCore;

namespace entityframeworkexample.Controllers

{

    public class StudentcodeController : Controller

    {

        private CollegeerpContext db;

        public StudentcodeController(CollegeerpContext db)

        {

            this.db = db;

        }

        public IActionResult Create()

        {

            return View();

        }

        [HttpPost]

        public IActionResult Create(Student obj)

        {

            db.Students.Add(obj);

            db.SaveChanges();

            ViewBag.Data = "Data Inserted Suceesfully";

            return RedirectToAction("Index");

        }

        public IActionResult Index()

        {

            var s = db.Students.ToList();  // select * from students

            return View(s);

        }

        public IActionResult EditStudent(int? id)

        {

            var s = db.Students.Find(id);  // select * from students

            return View(s);

        }

        [HttpPost]

        public IActionResult EditStudent(Student obj)

        {

            db.Entry(obj).State = EntityState.Modified;

            db.SaveChanges();

            return RedirectToAction("Index");

        }

        public IActionResult DeleteStudent(int? id)

        {

            var s = db.Students.Find(id);  // select * from students

            return View(s);

        }

        [HttpPost]

        public IActionResult DeleteStudent(Student obj)

        {

            db.Students.Remove(obj);

            db.SaveChanges();

            return RedirectToAction("Index");

        }

    }

}


Code for Index.cshtml
@model IEnumerable<entityframeworkexample.Models.DB.Student>;
@Html.ActionLink("Add Student","Create")
<table border="1">
    <tr><td>RNO</td><td>NAME</td><td>BRANCH</td><td>Fees</td></tr>
    @foreach(var item in Model)
    {
        <tr><td>@Html.DisplayFor(key=>item.Rno)</td>
            <td>@Html.DisplayFor(key=>item.Sname)</td>
            <td>@Html.DisplayFor(key=>item.Branch)</td>
            <td>@Html.DisplayFor(key=>item.Fees)</td>
            <td>@Html.ActionLink("Edit","EditStudent",new{id=item.Rno}) </td>
            <td>@Html.ActionLink("Delete","DeleteStudent",new{id=item.Rno}) </td>
        </tr>
    }
</table>


Code for create.cshtml:-


@model entityframeworkexample.Models.DB.Student
@{
    ViewData["Title"] = "Create";
}

<h1>Create</h1>
@using(Html.BeginForm())
{
    @Html.TextBoxFor(a=>a.Rno) <br />
    @Html.TextBoxFor(a=>a.Sname) <br />
    @Html.TextBoxFor(a=>a.Branch) <br />
    @Html.TextBoxFor(a=>a.Fees) <br />
    <input type="submit" name="btnsubmit" value="Click" />
}
 @ViewBag.Data

Code for Edit.cshtml:-

@model entityframeworkexample.Models.DB.Student;
@using(Html.BeginForm())
{
<table border="1">
 <tr><td>RNO</td><td>@Html.TextBoxFor(a=>Model.Rno)</td></tr>
    <tr><td>NAME</td><td>@Html.TextBoxFor(key=>Model.Sname)</td></tr>
    <tr><td>BRANCH</td><td>@Html.TextBoxFor(key=>Model.Branch)</td></tr>
    <tr><td>Fees</td><td>@Html.TextBoxFor(key=>Model.Fees)</td></tr>
 <tr><td></td><td><input type="submit" name="btnsubmit" value="Click" /></td></tr>           
</table>
}

@model entityframeworkexample.Models.DB.Student;
@{
    ViewData["Title"] = "DeleteStudent";
}

<h1>Are you sure to  Delete Student</h1>

@using (Html.BeginForm())
{
    <table border="1">
        <tr><td>RNO</td><td>@Html.DisplayFor(a=>Model.Rno)  @Html.HiddenFor(a=>Model.Rno) </td></tr>
        <tr><td>NAME</td><td>@Html.DisplayFor(key=>Model.Sname) @Html.HiddenFor(a=>Model.Sname)</td></tr>
        <tr><td>BRANCH</td><td>@Html.DisplayFor(key=>Model.Branch) @Html.HiddenFor(a=>Model.Branch)</td></tr>
        <tr><td>Fees</td><td>@Html.DisplayFor(key=>Model.Fees) @Html.HiddenFor(a=>Model.Fees)</td></tr>
        <tr><td></td><td><input type="submit" name="btnsubmit" value="Click" /></td></tr>
    </table>
}







تعليقات

المشاركات الشائعة من هذه المدونة

DSA in C# | Data Structure and Algorithm using C#

  DSA in C# |  Data Structure and Algorithm using C#: Lecture 1: Introduction to Data Structures and Algorithms (1 Hour) 1.1 What are Data Structures? Data Structures are ways to store and organize data so it can be used efficiently. Think of data structures as containers that hold data in a specific format. Types of Data Structures: Primitive Data Structures : These are basic structures built into the language. Example: int , float , char , bool in C#. Example : csharp int age = 25;  // 'age' stores an integer value. bool isStudent = true;  // 'isStudent' stores a boolean value. Non-Primitive Data Structures : These are more complex and are built using primitive types. They are divided into: Linear : Arrays, Lists, Queues, Stacks (data is arranged in a sequence). Non-Linear : Trees, Graphs (data is connected in more complex ways). Example : // Array is a simple linear data structure int[] number...

JSP Page design using Internal CSS

  JSP is used to design the user interface of an application, CSS is used to provide set of properties. Jsp provide proper page template to create user interface of dynamic web application. We can write CSS using three different ways 1)  inline CSS:-   we will write CSS tag under HTML elements <div style="width:200px; height:100px; background-color:green;"></div> 2)  Internal CSS:-  we will write CSS under <style> block. <style type="text/css"> #abc { width:200px;  height:100px;  background-color:green; } </style> <div id="abc"></div> 3) External CSS:-  we will write CSS to create a separate file and link it into HTML Web pages. create a separate file and named it style.css #abc { width:200px;  height:100px;  background-color:green; } go into Jsp page and link style.css <link href="style.css"  type="text/css" rel="stylesheet"   /> <div id="abc"> </div> Exam...

Top 50 Most Asked MERN Stack Interview Questions and Answers for 2025

 Top 50 Most Asked MERN Stack Interview Questions and Answers for 2025 Now a days most of the IT Company asked NODE JS Question mostly in interview. I am creating this article to provide help to all MERN Stack developer , who is in doubt that which type of question can be asked in MERN Stack  then they can learn from this article. I am Shiva Gautam,  I have 15 Years of experience in Multiple IT Technology, I am Founder of Shiva Concept Solution Best Programming Institute with 100% Job placement guarantee. for more information visit  Shiva Concept Solution 1. What is the MERN Stack? Answer : MERN Stack is a full-stack JavaScript framework using MongoDB (database), Express.js (backend framework), React (frontend library), and Node.js (server runtime). It’s popular for building fast, scalable web apps with one language—JavaScript. 2. What is MongoDB, and why use it in MERN? Answer : MongoDB is a NoSQL database that stores data in flexible, JSON-like documents. It...