Database First Approach in Asp.Net Core
Packages
- "Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.17"
- "Microsoft.EntityFrameworkCore.Tools" Version="5.0.17"
- "Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="5.0.2"
Controllers[Folder]
StudentsController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using DatabaseFirstEFCore.Models;
namespace DatabaseFirstEFCore.Controllers
{
public class StudentsController : Controller
{
private readonly studentdbContext _context;
public StudentsController(studentdbContext context)
{
_context = context;
}
// GET: Students
public async Task<IActionResult> Index()
{
return View(await _context.Students.ToListAsync());
}
// GET: Students/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var student = await _context.Students
.FirstOrDefaultAsync(m => m.Id == id);
if (student == null)
{
return NotFound();
}
return View(student);
}
// GET: Students/Create
public IActionResult Create()
{
return View();
}
// POST: Students/Create
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Name,Gender,Age,Standard")] Student student)
{
if (ModelState.IsValid)
{
_context.Add(student);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(student);
}
// GET: Students/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var student = await _context.Students.FindAsync(id);
if (student == null)
{
return NotFound();
}
return View(student);
}
// POST: Students/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,Name,Gender,Age,Standard")] Student student)
{
if (id != student.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(student);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!StudentExists(student.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(student);
}
// GET: Students/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var student = await _context.Students
.FirstOrDefaultAsync(m => m.Id == id);
if (student == null)
{
return NotFound();
}
return View(student);
}
// POST: Students/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var student = await _context.Students.FindAsync(id);
_context.Students.Remove(student);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool StudentExists(int id)
{
return _context.Students.Any(e => e.Id == id);
}
}
}
Models[Fodler]
Student.cs
using System;
using System.Collections.Generic;
#nullable disable
namespace DatabaseFirstEFCore.Models
{
public partial class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public int? Age { get; set; }
public int? Standard { get; set; }
}
}
studentdbContext.cs
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
#nullable disable
namespace DatabaseFirstEFCore.Models
{
public partial class studentdbContext : DbContext
{
public studentdbContext()
{
}
public studentdbContext(DbContextOptions<studentdbContext> options)
: base(options)
{
}
public virtual DbSet<Student> Students { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("Server=CHETUIWK0541\\SQL2019NEW;Database=studentdb;Trusted_Connection=True;");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>(entity =>
{
entity.ToTable("student");
entity.Property(e => e.Id).HasColumnName("id");
entity.Property(e => e.Age).HasColumnName("age");
entity.Property(e => e.Gender)
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnName("gender");
entity.Property(e => e.Name)
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnName("name");
entity.Property(e => e.Standard).HasColumnName("standard");
});
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
}
Views[Folder]
Students
Create.cshtml
@model DatabaseFirstEFCore.Models.Student
@{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>Student</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Gender" class="control-label"></label>
<input asp-for="Gender" class="form-control" />
<span asp-validation-for="Gender" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Age" class="control-label"></label>
<input asp-for="Age" class="form-control" />
<span asp-validation-for="Age" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Standard" class="control-label"></label>
<input asp-for="Standard" class="form-control" />
<span asp-validation-for="Standard" 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");}
}
Delete.cshtml
@model DatabaseFirstEFCore.Models.Student
@{
ViewData["Title"] = "Delete";
}
<h1>Delete</h1>
<h3>Are you sure you want to delete this?</h3>
<div>
<h4>Student</h4>
<hr />
<dl class="row">
<dt class = "col-sm-2">
@Html.DisplayNameFor(model => model.Name)
</dt>
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.Name)
</dd>
<dt class = "col-sm-2">
@Html.DisplayNameFor(model => model.Gender)
</dt>
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.Gender)
</dd>
<dt class = "col-sm-2">
@Html.DisplayNameFor(model => model.Age)
</dt>
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.Age)
</dd>
<dt class = "col-sm-2">
@Html.DisplayNameFor(model => model.Standard)
</dt>
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.Standard)
</dd>
</dl>
<form asp-action="Delete">
<input type="hidden" asp-for="Id" />
<input type="submit" value="Delete" class="btn btn-danger" /> |
<a asp-action="Index">Back to List</a>
</form>
</div>
Details.cshtml
@model DatabaseFirstEFCore.Models.Student
@{
ViewData["Title"] = "Details";
}
<h1>Details</h1>
<div>
<h4>Student</h4>
<hr />
<dl class="row">
<dt class = "col-sm-2">
@Html.DisplayNameFor(model => model.Name)
</dt>
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.Name)
</dd>
<dt class = "col-sm-2">
@Html.DisplayNameFor(model => model.Gender)
</dt>
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.Gender)
</dd>
<dt class = "col-sm-2">
@Html.DisplayNameFor(model => model.Age)
</dt>
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.Age)
</dd>
<dt class = "col-sm-2">
@Html.DisplayNameFor(model => model.Standard)
</dt>
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.Standard)
</dd>
</dl>
</div>
<div>
<a asp-action="Edit" asp-route-id="@Model.Id">Edit</a> |
<a asp-action="Index">Back to List</a>
</div>
Edit.cshtml
@model DatabaseFirstEFCore.Models.Student
@{
ViewData["Title"] = "Edit";
}
<h1>Edit</h1>
<h4>Student</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Edit">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="Id" />
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Gender" class="control-label"></label>
<input asp-for="Gender" class="form-control" />
<span asp-validation-for="Gender" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Age" class="control-label"></label>
<input asp-for="Age" class="form-control" />
<span asp-validation-for="Age" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Standard" class="control-label"></label>
<input asp-for="Standard" class="form-control" />
<span asp-validation-for="Standard" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Index.cshtml
@model IEnumerable<DatabaseFirstEFCore.Models.Student>
@{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Gender)
</th>
<th>
@Html.DisplayNameFor(model => model.Age)
</th>
<th>
@Html.DisplayNameFor(model => model.Standard)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Gender)
</td>
<td>
@Html.DisplayFor(modelItem => item.Age)
</td>
<td>
@Html.DisplayFor(modelItem => item.Standard)
</td>
<td>
<a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
<a asp-action="Details" asp-route-id="@item.Id">Details</a> |
<a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
</td>
</tr>
}
</tbody>
</table>
Startup.cs
using DatabaseFirstEFCore.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DatabaseFirstEFCore
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<studentdbContext>(options => options.UseSqlServer("Server=CHETUIWK0541\\SQL2019NEW;Database=studentdb;Trusted_Connection=True;"));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Students}/{action=Index}/{id?}");
});
}
}
}
0 Comments