Skip to content

Commit

Permalink
add Entity framework
Browse files Browse the repository at this point in the history
  • Loading branch information
sthsuyash committed Apr 18, 2024
1 parent ed0ce85 commit d7ffa54
Show file tree
Hide file tree
Showing 25 changed files with 686 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using Microsoft.AspNetCore.Mvc;
using PrimeEFCoreB.Models;
using System.Diagnostics;

namespace PrimeEFCoreB.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;

public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}

public IActionResult Index()
{
return View();
}

public IActionResult Privacy()
{
return View();
}

[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
using Microsoft.AspNetCore.Mvc;
using PrimeEFCoreB.Models;

/*
* Controller is responsible for handling incoming HTTP requests
* and sending response to the browser.
*/
namespace PrimeEFCoreB.Controllers
{
public class StudentController : Controller
{
// setting context class on controller
// context is used to interact with the database
private readonly StudentContext sc;

// constructor to initialize context class
public StudentController(StudentContext sc)
{
this.sc = sc;
}

// insertStudent method is used to create form in view. it uses get
[HttpGet]
public IActionResult InsertStudent()
{
return View();
}

// accept form data and insert into the database table
[HttpPost]
public IActionResult InsertStudent(Student s)
{
var student = new Student()
{
Id = Guid.NewGuid(), // auto generated
Name = s.Name,
Gender = s.Gender,
Address = s.Address,
Faculty = s.Faculty
};
sc.Students.Add(student);
sc.SaveChanges();
return RedirectToAction("Index");
}

// displaying data
public IActionResult Index()
{
// data will be displayed in index.cshtml
// data from table will be converted into list and sent to view
var viewStd = sc.Students.ToList();
return View(viewStd);
}

// action method to update operation
[HttpGet]
public IActionResult Edit(Guid id)
{
// check if id sent from view is matched with database record or not
// if matched, send the data to set method of EditStudent
var editStudentsData = sc.Students.FirstOrDefault(x => x.Id == id);
if (editStudentsData != null)
{
var editStudent = new Student()
{
Id = editStudentsData.Id,
Name = editStudentsData.Name,
Gender = editStudentsData.Gender,
Address = editStudentsData.Address,
Faculty = editStudentsData.Faculty
};
return View(editStudent);
}
else
{
return RedirectToAction("Index");
}
}

[HttpPost]
public IActionResult Edit(Student student)
{
// check if id of editStudent persist or not in database
// save changes in database
var editStds = sc.Students.Find(student.Id);
if (editStds != null)
{
editStds.Id = student.Id;
editStds.Name = student.Name;
editStds.Address = student.Address;
editStds.Gender = student.Gender;
editStds.Faculty = student.Faculty;
sc.SaveChanges();
}
return RedirectToAction("Index");
}
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace PrimeEFCoreB.Migrations
{
/// <inheritdoc />
public partial class Initial : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Students",
columns: table => new
{
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
Name = table.Column<string>(type: "nvarchar(max)", nullable: false),
Gender = table.Column<string>(type: "nvarchar(max)", nullable: false),
Address = table.Column<string>(type: "nvarchar(max)", nullable: false),
Faculty = table.Column<string>(type: "nvarchar(max)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Students", x => x.Id);
});
}

/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Students");
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using PrimeEFCoreB.Models;

#nullable disable

namespace PrimeEFCoreB.Migrations
{
[DbContext(typeof(StudentContext))]
partial class StudentContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 128);

SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);

modelBuilder.Entity("PrimeEFCoreB.Models.Student", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("Address")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Faculty")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Gender")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Students");
});
#pragma warning restore 612, 618
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace PrimeEFCoreB.Models
{
public class ErrorViewModel
{
public string? RequestId { get; set; }

public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
namespace PrimeEFCoreB.Models
{
/*
* Entity framework act as bridge to connect with external data source like sql server when using asp.net core or MVC application.
* It uses object relational mapping to interact with the database.
* which means all the operation of database are done by create class
* and object like table, db, tables, column, CRUD operation
*
* To use entity framework, two pacakges needs to be downloaded
* EntityFrameworkCore.SqlServer and EntityFrameworkCore.Tools
*/
public class Student
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string Address { get; set; }
public string Faculty { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using Microsoft.EntityFrameworkCore;

namespace PrimeEFCoreB.Models
{
/*
* This context class is responsible for creating object of server (sql server) and
* Creating table (setting columns of table of database)
* this class should inherit DbContext class
*/
public class StudentContext : DbContext
{
// creating constructor that will set the object of server
public StudentContext(DbContextOptions<StudentContext> options) : base(options) { }

// setting column of table. for this we have to use const of DbSet() class
public DbSet<Student> Students { get; set; }
// <Student>:modelclass Students:tableName
// here Student is model class that will set column of table
// Student is table name

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.9.34714.143
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PrimeEFCoreB", "PrimeEFCoreB.csproj", "{A037DAB3-5E0C-497B-AB7C-771A65C7E712}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{A037DAB3-5E0C-497B-AB7C-771A65C7E712}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A037DAB3-5E0C-497B-AB7C-771A65C7E712}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A037DAB3-5E0C-497B-AB7C-771A65C7E712}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A037DAB3-5E0C-497B-AB7C-771A65C7E712}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {01C1A4DA-FA40-4A48-867E-AAD4F24E539B}
EndGlobalSection
EndGlobal
Loading

0 comments on commit d7ffa54

Please sign in to comment.