Asp.Net 6.0 Core MVC Code First Approach Using Entity Framework CRUD Operations

I am  using  visualstudio2022..sqlserver

select   c#   ,all platform,    web 

and then select  asp.net (model-View-Controller)

and then click next

after give project name CRUDOperationsDemo       AND SELECT    FRAMEWORK   .NET6VERSION

AND THEN ON CREATE BUTTON 

AFTER NEXT LOOKS YOUR SOLUTION EXPLORER  FILEES

YOU HAVE FOLDER MODEL VIEW S AND CONTROLLER

AND THEN RIGHT  CLICK ON MODEL FOLDER AND ADD CLASS thats  NAME Department

simillalry create another class name named Employee

codeof department .cs file

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace CURDOprationsDimo.Models
{
[Table("Departments",Schema ="HR")]
public class Department
{
[Key][Display(Name="ID")]
public int DepartmentId { get; set; }
[Required]
[Display(Name="Department Name")]
[Column(TypeName = "varchar(200)")]
public string DepartmentName { get; set; } = string.Empty;
}
} and then solve some potential fixes if so and then Employee.cs file code
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace CURDOprationsDimo.Models
{
[Table("Employees", Schema ="HR")]
public class Employee
{
[Key]
[Display(Name="ID")]
public int? EmployeeId { get; set; }
[Required]
[Display(Name = "Name")]
[Column(TypeName ="varchar(250)")]
public string EmployeeName { get; set; } = string.Empty;
[Display(Name ="Image User")]
[Column (TypeName ="varchar(250)")]
public string? ImageUser { get; set; }
[Required]
[Display(Name ="Birth Date")]
[DataType(DataType.Date)]
public DateTime BirthDate { get; set; }
[Required,Display(Name ="Salary"),Column(TypeName ="decimal(12,2)")]
public decimal Salary { get; set; }
[Required]
[Display(Name ="Hiring Date")]
[DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:dd-MMMM-yyyy}")]
public DateTime HiringDate { get; set; }
[Required]
[Display(Name ="National ID")]
[Column (TypeName ="varchar(14)")]
[MaxLength(14)]
[MinLength(14)]
public string NationalId { get; set; } = string.Empty;
[Display(Name ="Department")]
public int DepartmentId { get; set; }
[ForeignKey("DepartmentId")]
public Department? Department { get; set; }
}
} and then right click to dependencies and then goes to manage nugetpackages and goes to browse options and then add these packages 1. Microsoft.EntityFrameworkCore 2. Microsoft.EntityFrameworkCore.Relational 3. Microsoft.EntityFrameworkCore.Design 4. Microsoft.EntityFrameworkCore.SqlServer 5. Microsoft.EntityFrameworkCore.Tools remember all versions should be above6.0 IF YOU WISH TO WANT ADD FOLDER THEN ADD DATA FOLDER OR AND THEN DB CONTEXT FILE OR ELSE RIGHT CLICK ON PROJECT AND ADD CLASS WITH NAMED CRUDDbContext.CS CODE GIVEN BELOW
using CURDOprationsDimo.Models;
using Microsoft.EntityFrameworkCore;
namespace CRUDOperationsDemo
{
public class CRUDDbContext : DbContext
{
public CRUDDbContext(DbContextOptions<CRUDDbContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
//modelBuilder.Entity<Employee>().ToTable("Employees", "HR");
}
public DbSet<Department> Departments { get; set; }
public DbSet<Employee> Employees { get; set; }
}
} AND THEN GOES ON APP SETTING .JSON FILES AFTER THE PROGRAM CODE ALLOWED HOST CLICK , ORGIVES COMMA AND THEN ENTER AND ADD THESE CODES
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"ConnectionDb": "server= DESKTOP-BBI83UQ\\SQLEXPRESS;Database=CRUDOperationDemo; Trusted_Connection=True"
}
} GIVES YOUR CONNECTION STRING ONLY CHANGED THE SERVER NAME AND DATABASE NAME :- AND THEN GOES TO PROGRAM FILES AND MAKES THAT CHANGED CODES GIVEN BELOW
using CRUDOperationsDemo;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddDbContext<CRUDDbContext>(option=>
option.UseSqlServer(builder.Configuration.GetConnectionString("ConnectionDb")));
//builder.Services.AddRazorPages().AddRazorRuntimeCompilation();
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=Employees}/{action=Index}/{id?}");
app.Run();
AND THEN GOES FOR PACKAGE MANAGER CONSOLE (IF YOU DID NT FIND THEN GOES TO TOOLS AND THEN MANAGE NUGET PACKAGES AND THEN YOU GET) CAREFULLY EXECUTE COMMAND 1. add-migration InitilazeData after wriiteen this command click enter and then you got popup and then click Build Succeeded and then you get migration files in solution exploerer 2. update-database after written done. goes TO YOR SQL SERVER AND FIND THAT DATABASE AND TABLE CLICK REFRESH AND THEN OPEN DEPARTMENT TABLES AND EMPLOYEES TABLES WITH RIGHT CLICK ON IT AND THEN CHOSSE EDIT TOP 200 ROWS IN DEPARTMENT FILLS SOME ID AS WELLAS HR, TECHINICIANS AND MARKETING . AFTER THAT FILSS EMPLOYEES DETAILS (REMENBER FILLING IN PROPER ORDER) AND MINIMUM FOUR YOU HAVE TO FILL AS USUAL [ IDINTITY SPECIFICATION IS YES IN ALL DEFAULT SERVER BUT YOU SHULD HAVE TO CHECK TO AVOID ANY CLAUSE)] AND AFTER THAT CLICK ON CONTROLLER FOLDER AND ADD MVCCONTROLLER EMPTY AND GIVES THAT NAME EmployeesController and after that goes on programm files files controller to Employees and then right click on the index where written public IActionResult Index() and then click on add view and then click on Razor view after that pop open then fill these data view name index template list model class Employee(webappCrud operation.model) and then click on the check boxes refrences scripts Use alayout and then next click on create and then you got thsese codes
@model IEnumerable<CURDOprationsDimo.Models.Employee>
@{
ViewData["Title"] = "Index";
}
<h1>Employees</h1>
<p>
<a asp-action="Create" class="btn btn-info">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.EmployeeId)
</th>
<th>
@Html.DisplayNameFor(model => model.EmployeeName)
</th>
<th>
@Html.DisplayNameFor(model => model.ImageUser)
</th>
<th>
@Html.DisplayNameFor(model => model.BirthDate)
</th>
<th>
@Html.DisplayNameFor(model => model.Salary)
</th>
<th>
@Html.DisplayNameFor(model => model.HiringDate)
</th>
<th>
@Html.DisplayNameFor(model => model.NationalId)
</th>
<th>
@Html.DisplayNameFor(model => model.DepartmentId)
</th>
<th>Events</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.EmployeeId)
</td>
<td>
@Html.DisplayFor(modelItem => item.EmployeeName)
</td>
<td>
<img src="images/@item.ImageUser"
style="width:35px;height:35px">
</td>
<td>
@Html.DisplayFor(modelItem => item.BirthDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.Salary)
</td>
<td>
@Html.DisplayFor(modelItem => item.HiringDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.NationalId)
</td>
<td>
@Html.DisplayFor(modelItem => item.Department.DepartmentName)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.EmployeeId }) |
@Html.ActionLink("Delete", "Delete", new { id=item.EmployeeId }
,new{onclick="return confirm('Are You Sure From Deleted... ?')"})
</td>
</tr>
}
</tbody>
</table>
and then click on EmployeesControllers .cs paste these code
public class EmployeesController : Controller
{
private readonly CRUDDbContext _context;
private readonly IWebHostEnvironment env;
public EmployeesController(CRUDDbContext context)
{
_context = context; } public IActionResult Index() { var Result = _context.Employees.ToList(); return View(Result); And then save and run these project you find index page where the data been stored is been available to you fetching from the database and then goes on wwww.root and right click and gives the foldernames as Images same as click on create and choose template create. and on template choose create option and in view also create and else will besame code of create file
@model CURDOprationsDimo.Models.Employee
@{
ViewData["Title"] = Model != null ? "Edit":"Create";
}
<h1>@ViewData["Title"] Employee</h1>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="@ViewData["Title"]" enctype="multipart/form-data">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input asp-for="EmployeeId" class="form-control" readonly/>
<input asp-for="ImageUser" hidden class="form-control" />
<div class="form-group">
<label asp-for="EmployeeName" class="control-label"></label>
<input asp-for="EmployeeName" class="form-control" />
<span asp-validation-for="EmployeeName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="ImageUser" class="control-label"></label>
<input type="file" asp-for="ImageUser" class="form-control" />
<span asp-validation-for="ImageUser" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="BirthDate" class="control-label"></label>
<input asp-for="BirthDate" class="form-control" />
<span asp-validation-for="BirthDate" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Salary" class="control-label"></label>
<input asp-for="Salary" class="form-control" />
<span asp-validation-for="Salary" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="HiringDate" class="control-label"></label>
<input asp-for="HiringDate" class="form-control" />
<span asp-validation-for="HiringDate" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="NationalId" class="control-label"></label>
<input asp-for="NationalId" class="form-control" />
<span asp-validation-for="NationalId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="DepartmentId" class="control-label"></label>
<select asp-for="DepartmentId" class="form-control"
asp-items="@(new SelectList(ViewBag.Departments,"DepartmentId","DepartmentName"))">
<option value="">Select Department Name ...</option>
</select>
<span asp-validation-for="DepartmentId" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
now addd the the code of the Employeescontroller.cs file code
using CRUDOperationsDemo;
using CURDOprationsDimo.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace CURDOprationsDimo.Controllers
{
public class EmployeesController : Controller
{
private readonly CRUDDbContext _context;
private readonly IWebHostEnvironment env;
public EmployeesController(CRUDDbContext context,IWebHostEnvironment env)
{
_context = context;
this.env = env;
}
public IActionResult Index()
{
var Result= _context.Employees.Include(x=>x.Department)
.OrderBy(x=>x.EmployeeName).ToList();
return View(Result);
}
public IActionResult Create()
{
ViewBag.Departments = _context.Departments.OrderBy(x => x.DepartmentName).ToList();
return View();
}
public IActionResult Edit(int? Id)
{
ViewBag.Departments = _context.Departments.OrderBy(x => x.DepartmentName).ToList();
var result = _context.Employees.Find(Id);
return View("Create", result);
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Employee model)
{
UploadImage(model);
if (ModelState.IsValid)
{
_context.Employees.Add(model);
_context.SaveChanges();
return RedirectToAction(nameof(Index));
}
ViewBag.Departments = _context.Departments.OrderBy(x => x.DepartmentName).ToList();
return View();
}
private void UploadImage(Employee model)
{
var file = HttpContext.Request.Form.Files;
if (file.Count() > 0)
{//@"wwwroot/"
string ImageName = Guid.NewGuid().ToString() + Path.GetExtension(file[0].FileName);
var filestream = new FileStream(Path.Combine(env.WebRootPath, "Images", ImageName), FileMode.Create);
file[0].CopyTo(filestream);
model.ImageUser = ImageName;
}
else if (model.ImageUser == null && model.EmployeeId == null)
{
model.ImageUser = "DefultImage.jpg";
}
else
{
model.ImageUser = model.ImageUser;
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Edit(Employee model)
{
UploadImage(model);
if (model != null)
{
_context.Employees.Update(model);
_context.SaveChanges();
return RedirectToAction(nameof(Index));
}
ViewBag.Departments = _context.Departments.OrderBy(x => x.DepartmentName).ToList();
return View(model);
}
public IActionResult Delete(int? Id)
{
var result = _context.Employees.Find(Id);
if (result != null)
{
_context.Employees.Remove(result);
_context.SaveChanges();
}
return RedirectToAction(nameof(Index));
}
}
}
and then code of the launch Settings.json files
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:37503",
"sslPort": 44355
}
},
"profiles": {
"CURDOprationsDimo": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7169;http://localhost:5169",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
} now the code of the files images folder save with


Comments

Popular Posts