Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 6

1. Connection with Database in appsettings.

json folder:
"ConnectionStrings": {
"defaultConnection": "Data Source=DESKTOP-CUUDSL9\\MSSQLSERVER01;Initial
Catalog=SaDb;Integrated Security=True;TrustServerCertificate=True"
},

2. Create a Model with required Properties

3. Dependencies Creation:
Create another folder named Data with a class called ApplicationContext. This class wud be used
to make connection with database since it would inherit DbContext.
public class ApplicationContext : DbContext
{
public ApplicationContext(DbContextOptions<ApplicationContext> options) : base(options)
{}

public DbSet<Employees> Employees { get; set; }


}///this is the table name we set it here

4. Dependencies Registration(Services) in program.cs file

builder.Services.AddDbContext<ApplicationContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("defaultConnection"));
});

5. Dependencies Injection in Controller:


private readonly ApplicationContext context;

public EmployeesController(ApplicationContext context)


{
this.context = context;
}
Use ctor to create a constructor here and ctrl +. Over ApplicationContext to create a private readonly
ApplicationContext context;

6. Create Views for Employees Controller by right clicking on Index within the EmployeesController and then
adding a new Razor View not Empty One.

7. Meanwhile, You can work on Shared Layout to add another link for Employees

<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Employees" asp-action="Index">Employees</a>
</li>

8. Now we can create a Table to enter data using NuGet Package manager present in the top option “Tools”. Fist
check whether all NuGet packages installed are of same versions or not. They need to be of same versions
otherwise they wouldn’t work well.
a. From NuGet Package manager, click on Package Manager Console : Now Try
PM> enable-migrations(press enter)
This checks if all the NuGet packages that you’ve installed are compatible or not. If not, it throws error.
b. PM> add-migration MyFirstMigration(press enter)
c. update-database(press enter)

9. Now Check the Database from Server Explorer, a Table with name “Employees” has been created now and it has
all 3 properties.
10. Right Click on the Employees table and click on show table data
11. Enter some data onto the table now and save it.
12. Now we need to perform CRUD operation starting with Reading operation:
13. Go inside Employees Controller and :

var data = context.Employees.ToList(); //data within Employees table is listed inside var data now and
returned to View
Note: we can check the breaking point here
return View(data);

14. Now we need to send this data to View in order to display it.
15. We can either display it simply or by using Table. Let’s use Table in Index.cshtml:

<table>
<tr>
<td>Id</td>
<td>Name</td>
<td>Salary</td>
</tr>

@foreach (var employee in Model)


{
<tr>
<td>@employee.EmployeeId</td>
<td>@employee.Name</td>
<td>@employee.Salary</td>
</tr>
}

</table>

This is our Read Operation

16. Now moving on to Create operation:


17. Let’s create a new Action named Create within the EmployeesController and also create its View.
Note: Always Remember View and Action name should be same
18. Add a Create link in Index File and then We need a Form To Store data now. Let’s use tag helper within Create
file: <a asp-action="Create">Create</a>
@model namespace.Models.modelname;

<form method="post" asp-action="Create">


<input asp-for="Name" />
<span asp-validation-for="Name"></span> //incase of any empty data passed
</br>
<input asp-for="Salary" />
<span asp-validation-for="Salary"></span> //incase of any empty data passed

</br>
<input type="submit" value="Submit" />
</form>

19. Now we need to place where would submit option take you. Let’s go to Employees Controller and generate a
[httppost] for Create option.

[HttpPost]
public IActionResult Create(Employees model)
{
if (ModelState.IsValid)
{
var data = new Employees
{
Name = model.Name,
Salary = model.Salary,
};
context.Employees.Add(data); //places into the database
context.SaveChanges();
return RedirectToAction("Index"); //returning back to index after making changes
}
else
{
return View(model);
}
}

Past Question related answer:


var data = new Employees {

EmployeeId = 3,

Name = "John",

Salary = 12000, };

context.Employee.Add(data);

context.SaveChanges();

return RedirectToAction("Index");

20. Moving on to Delete and Edit/Update Operations


21. Add link for both in Index.cshtml within the foreach loop:
<td>
<a asp-action="Delete" asp-route id="@employee.EmployeeId">Delete</a>
<a asp-action="Edit" asp-route-id="@employee.EmployeeId">Edit</a>
</td>

22. Now we need to define this delete action within Employees Controller:
public IActionResult Delete(int id)

var emp = context.Employees.SingleOrDefault(x => x.EmployeeId == id);

if (emp != null)

context.Employees.Remove(emp);

context.SaveChanges();

return RedirectToAction("Index");

23. Now similarly for Edit/update, lets add another action within the Employees Controller for Edit action:
24. [httpget]
public IActionResult Edit(int id)
{
var emp = context.Employees.SingleOrDefault(x => x.EmployeeId == id);

if (emp == null)
{
return NotFound(); // Return 404 if employee with specified ID is not found
}

var result = new Employees()


{
Name = emp.Name,
Salary = emp.Salary,
};

return View(result);
}
25. We need a View for Edit as well so lets create that View.

@model WebAppCore.Models.Employees

@{

ViewData["Title"] = "Edit";

}
<h1>Edit</h1>

<form method="post" asp-action="Edit">

<input type="hidden" asp-for="EmployeeId" /> <!-- Include hidden input for EmployeeId -->

<input asp-for="Name" />

<span asp-validation-for="Name"></span>

<br />

<input asp-for="Salary" />

<span asp-validation-for="Salary"></span>

<br />

<input type="submit" value="Submit" />

</form>

Since after editing new Name and Salary wud be updated so we again need a new Action Controller for this Edit i.e
[httpPost]:

[HttpPost]

public IActionResult Edit(Employees model)

if (ModelState.IsValid)

var employee = context.Employees.SingleOrDefault(emp => emp.EmployeeId == model.EmployeeId);

if (employee != null)

employee.Name = model.Name;

employee.Salary = model.Salary;

context.Employees.Update(employee);

context.SaveChanges();

return RedirectToAction("Index");
}

You might also like