Posts

Unit of work with generic repository in .NET with EF Core

Image
  The Unit of Work Pattern is all about coordinated changes to the database. It groups multiple operations, such as inserts, updates, and deletes, into one transaction. This simply means that all the changes are done together as a complete action, or they all don’t happen at all. In case something goes wrong in one of the operations, the whole transaction rolls back and keeps the database consistent by not allowing partial updates. This makes it easy to handle errors and ensures reliable data. 💻 Source code: https://github.com/rd003/DotnetUowDemo Tools needed .NET 8 SDK (Maybe .net 9 would be released at the time you are reading it, it would also work in .net 9. However older versions like 6 and 7 will also work). Visual Studio Code With C# Dev kit extension. Microsoft SQL Server. First and foremost, we are going to create a new project. Open the terminal or command prompt and run the following commands one by one. dotnet new sln -o DotnetUowDemo cd DotnetUowDemo dotnet new webapi

Predicate in c# and Its use case

Image
Predicate delegate takes only one argument and returns a boolean value.  Example: static void Main () { // return true if passed argument is greater than 4 Predicate< int > greaterThanFour = (n) => n> 4 ; Console.WriteLine(greaterThanFour( 4 )); //false } It is the very basic example of predicate, which returns true if number is greater than four otherwise it returns false. You already have used the predicate if you have used the LINQ. List<Order> orders = new List<Order> { new Order { OrderId = 101 , Status = "Pending" }, new Order { OrderId = 102 , Status = "Completed" }, new Order { OrderId = 103 , Status = "Cancelled" }, new Order { OrderId = 104 , Status = "Completed" } }; // Find order with id 104 var order = orders.Find(o => o.OrderId == 104 ); The  find  method takes the  predicate  as the parameter. Which returns  true  if it finds the  order with id 104 . Which i

Registering Multiple Implementation With Same Interface

Image
We have an interface with name  IVehicle public interface IVehicle { string Type { get ; set ; } } We have 3 Implementations of this interface  Car , Van  and  Truck . public class Car : IVehicle { public string Type { get ; set ; } = "Car" ; } public class Truck : IVehicle { public string Type { get ; set ; } = "Truck" ; } public class Van : IVehicle { public string Type { get ; set ; } = "Van" ; } We have a  CarController , where we want to use the  Car  implementation of  IVehicle . [ Route( "/api/cars" ) ] [ ApiController ] public class CarController : ControllerBase { private IVehicle _vehicle; public CarController ( IVehicle vehicle ) { _vehicle = vehicle; } } It is a usual approach to inject any service. But, in our case  IVehcle  have 3 implementations.However, determining which implementation is in use is not straightforward with our current method. To address this,