0% found this document useful (0 votes)
18 views8 pages

10 07 24

The document discusses Dependency Injection in .NET, outlining three methods for registering dependencies: AddSingleton, AddTransient, and AddScoped, each defining the service's lifetime. It also covers the implementation of an Employee model and an IEmployee interface, along with an EmployeeUtility class that manages employee data. Additionally, it introduces Entity Framework Core, detailing its features, the DbContext class, and the Database First Approach for integrating databases with ASP.NET Core applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views8 pages

10 07 24

The document discusses Dependency Injection in .NET, outlining three methods for registering dependencies: AddSingleton, AddTransient, and AddScoped, each defining the service's lifetime. It also covers the implementation of an Employee model and an IEmployee interface, along with an EmployeeUtility class that manages employee data. Additionally, it introduces Entity Framework Core, detailing its features, the DbContext class, and the Database First Approach for integrating databases with ASP.NET Core applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

[11:24 AM] T V S Koushik

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.

[11:24 AM] T V S Koushik

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; }

[Required(ErrorMessage ="EmpName Required")]


[RegularExpression("^[A-Za-z]{3,15}$",ErrorMessage ="Invalid EmpName")]
public string EmpName { get; set; }

[Range(10000,999999,ErrorMessage ="Invalid Salary")]


public int Salary { 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; namespa... by T V S KoushikT V S Koushik11:25 AM

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 });
}

public List<Employee> GetEmployees()


{
return empList;
}

public Employee FindEmployee(int id)


{
return empList.Find(e => e.EmpID == id);
}

public bool AddEmployee(Employee emp)


{
if(emp != null)
{
empList.Add(emp);
return true;
}
return false;
}

public bool EditEmployee(int id, Employee emp)


{
Employee e = empList.Find(em => em.EmpID == id);
if(e != null)
{
e.EmpName = emp.EmpName;
e.Salary = emp.Salary;
return true;
}
return false;
}
public bool DeleteEmployee(int id)
{
Employee e = empList.Find(em => em.EmpID == id);
if (e != null)
{
empList.Remove(e);
return true;
}
return false;
}
}
}

using Microsoft.AspNetCore.Mvc; using Dep... by T V S KoushikT V S Koushik11:25 AM

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());
}

public IActionResult Find(int id)


{
return View(employee.FindEmployee(id));
}

public IActionResult Add()


{
return View();
}

[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();
}
}
}

has context menu


[12:35 PM] T V S Koushik
Entity Framework Core

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

DbContext class is an integral part of EF, which is a representation of database.

DbContext class performs following tasks

 Managing Database connections


 Configure model & relationships
 Querying database
 Saving data to database
 Change tracking
 Caching

DbSet property -> which is a representation of database table.

EntityFramework core development approaches

EF core supports 2 development approaches

 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.

[12:35 PM] T V S Koushik


Database First Approach

Step-1: Have the Database ready in SQL Server

Step-2: Create an MVC project in ASP.Net Core

Step-3: Download the below Nuget packages

 Microsoft.EntityFrameworkCore.SqlServer -> Data Provider


 Microsoft.EntityFrameworkCore.Tools -> To Run migration commands

Step-4: Run the below migration command in package manager console window, to
auto generate required DbContext & domain classes.

 Scaffold-DbContext “<connection string>”


Microsoft.EntityFrameworkCore.SqlServer -outputDir Models

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));
}

}
}

has context menu

has context menu

You might also like