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

0

 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>
}







Post a Comment

0Comments

POST Answer of Questions and ASK to Doubt

Post a Comment (0)