10 07 24
10 07 24
Dependency Injection
Provides 3 methods to register dependencies. The method that we use determines
the life time of the registered service.
• AddSingleton() -> Will create and share only single instance of the service
throughout the life time of the application
• AddTransient() -> Creates the instance of the service every time the application
asks for it.
• AddScoped() -> Creates instance of the service once per request.
using System.ComponentModel.DataAnnotations;
namespace DependencyInjectionDemo.Models
{
public class Employee
{
[Required(ErrorMessage ="EmpID Required")]
[RegularExpression("^[0-9]{3}$",ErrorMessage ="Invalid EmpID")]
public int EmpID { get; set; }
using System.Collections.Generic;
namespace DependencyInjectionDemo.Models
{
public interface IEmployee
{
List<Employee> GetEmployees();
Employee FindEmployee(int id);
bool AddEmployee(Employee e);
bool EditEmployee(int id, Employee e);
bool DeleteEmployee(int id);
}
}
using System.Collections.Generic;
namespace DependencyInjectionDemo.Models
{
public class EmployeeUtility : IEmployee
{
public List<Employee> empList;
public EmployeeUtility()
{
empList = new List<Employee>();
empList.Add(new Employee() { EmpID = 111, EmpName = "Koushik", Salary =
12345 });
empList.Add(new Employee() { EmpID = 222, EmpName = "Karthik", Salary =
23456 });
empList.Add(new Employee() { EmpID = 333, EmpName = "Kiran", Salary =
34567 });
empList.Add(new Employee() { EmpID = 444, EmpName = "Kalyani", Salary =
45678 });
}
using Microsoft.AspNetCore.Mvc;
using DependencyInjectionDemo.Models;
namespace DependencyInjectionDemo.Controllers
{
public class EmployeeController : Controller
{
IEmployee employee;
public EmployeeController(IEmployee _employee)
{
employee = _employee;
}
public IActionResult Index()
{
return View(employee.GetEmployees());
}
[HttpPost]
public IActionResult Add(Employee emp)
{
if (ModelState.IsValid)
{
if (employee.AddEmployee(emp) == true)
{
return RedirectToAction("Index");
}
}
return View();
}
public IActionResult Edit(int id)
{
return View(employee.FindEmployee(id));
}
[HttpPost]
public IActionResult Edit(int id, Employee emp)
{
if (ModelState.IsValid)
{
if (employee.EditEmployee(id, emp) == true)
{
return RedirectToAction("Index");
}
}
return View();
}
public IActionResult Delete(int id)
{
return View(employee.FindEmployee(id));
}
[HttpPost]
public IActionResult Delete(int id, Employee emp)
{
if (employee.DeleteEmployee(id) == true)
{
return RedirectToAction("Index");
}
return View();
}
}
}
Entity Framework is an open source object relation mapper (ORM) that enables .Net
developers to work with a database using .Net objects
Features of EF
Cross Platform
Modeling -> EF creates an EDM (Entity Data Model) with get & set properties
for different datatypes. EF uses these models when querying or saving the
data to the underlying database.
Querying -> EF allows developers to use LINQ to retrieve data from underlying
database.
Change Tracking
Saving -> SaveChanges() -> Open Db connection, Auto generate Insert,
Update, delete queries depending on the changes made to the Entity classes.,
Executes them in the DB, Closes the connection
Caching
Migrations -> Migrations are set of commands used to auto-generate the
required code in EF
DbContext class
Code First Approach -> EF core API creates the database and tables using
migration commands as per the configuration provided in DbContext class &
domain classes
Database First Approach -> EF core API creates the domain and DbContext
classes based on the existing database using migration commands.
Step-4: Run the below migration command in package manager console window, to
auto generate required DbContext & domain classes.
Step-5: as the Model is ready, create a controller and call the respective methods in
the controller..
using EFCoreCodeFirstApproach.Models;
using Microsoft.AspNetCore.Mvc;
namespace EFCoreCodeFirstApproach.Controllers
{
public class CustomerController : Controller
{
CustomerDbContext context;
public CustomerController(CustomerDbContext _context)
{
context = _context;
}
public IActionResult Index()
{
return View(context.Customers);
}
public IActionResult Create()
{
return View();
}
[HttpPost]
public IActionResult Create(Customer customer)
{
if (customer != null)
{
context.Customers.Add(customer);
context.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
public IActionResult Edit(int id)
{
return View(context.Customers.Find(id));
}
[HttpPost]
public IActionResult Edit(int id, Customer emp)
{
Customer em = context.Customers.Find(id);
if (em != null)
{
em.Name = emp.Name;
em.Email = emp.Email;
context.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
public IActionResult Delete(int id)
{
return View(context.Customers.Find(id));
}
[HttpPost]
public IActionResult Delete(int id, Customer emp)
{
Customer em = context.Customers.Find(id);
if (em != null)
{
context.Customers.Remove(em);
context.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
public IActionResult Details(int id)
{
return View(context.Customers.Find(id));
}
}
}