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

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







تعليقات

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

Uncontrolled form input in React-JS

  Uncontrolled form input in React-JS? If we want to take input from users without any separate event handling then we can uncontrolled the data binding technique. The uncontrolled input is similar to the traditional HTML form inputs. The DOM itself handles the form data. Here, the HTML elements maintain their own state that will be updated when the input value changes. To write an uncontrolled component, you need to use a ref to get form values from the DOM. In other words, there is no need to write an event handler for every state update. You can use a ref to access the input field value of the form from the DOM. Example of Uncontrolled Form Input:- import React from "react" ; export class Info extends React . Component {     constructor ( props )     {         super ( props );         this . fun = this . fun . bind ( this ); //event method binding         this . input = React . createRef ();...

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

JDBC using JSP and Servlet

JDBC means Java Database Connectivity ,It is intermediates from Application to database. JDBC has different type of divers and provides to communicate from database server. JDBC contain four different type of approach to communicate with Database Type 1:- JDBC-ODBC Driver Type2:- JDBC Vendor specific Type3 :- JDBC Network Specific Type4:- JDBC Client-Server based Driver  or JAVA thin driver:- Mostly we prefer Type 4 type of Driver to communicate with database server. Step for JDBC:- 1  Create Database using MYSQL ,ORACLE ,MS-SQL or any other database 2   Create Table using database server 3   Create Form according to database table 4  Submit Form and get form data into servlet 5  write JDBC Code:-     5.1)   import package    import java.sql.*     5.2)  Add JDBC Driver according to database ide tools     5.3)  call driver in program         ...