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);
}
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; }
}
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");
}
}
}
POST Answer of Questions and ASK to Doubt