Feeds:
Posts
Comments

Archive for April, 2024

Here is an example of the Repository pattern in C# using CRUD operations. This pattern allows switching between different storage implementations such as different databases (such as MS SQL, Oracle), in memory database etc. Any simple type T can be used when implementing the contract.

Generic Interface:

 public interface IRespository<T>
 {
     T GetById(int id);
     T AddOrUpdate(T entity);
     void Delete(T entity);
     IEnumerable<T> GetAll();
 }

Example of a Concrete implementation:

public class RentalBookingEventRepository : IRespository<BookingEventDAO>
{
    // Sample dictionary for storing the data. key = bookingnumber
    private ConcurrentDictionary<string, ReturnEventDAO> _returnEvents = 
       new ConcurrentDictionary<string, ReturnEventDAO>();

 public BookingEventDAO GetById(int id)
 {
    // TODO
    throw new NotImplementedException();
 }

 public BookingEventDAO GetByBookingNumber(string bookingNumber)
 {
    if (string.IsNullOrEmpty(bookingNumber)) 
       throw new ArgumentNullException(nameof(bookingNumber));

    // TODO Assumes always works, should be handled. 
    _bookingEvents.TryGetValue(bookingNumber, out var bookingEvent);

    return bookingEvent;
 }
 
 public BookingEventDAO AddOrUpdate(BookingEventDAO bookingEvent)
 {
    if (bookingEvent == null)
       throw new ArgumentNullException(nameof(bookingEvent));

    var bookingnumber = string.IsNullOrEmpty(bookingEvent.BookingNumber) ?
       Guid.NewGuid().ToString() : bookingEvent.BookingNumber;

    // TODO Assumes always works, should be handled.
    _bookingEvents.AddOrUpdate(
       bookingnumber,
       bookingEvent,
       (bookingnumber, existingEvent) =>
    {
       existingEvent.CarCategory = bookingEvent.CarCategory;
       existingEvent.RentalStartDate = bookingEvent.RentalStartDate;
       existingEvent.Milage = bookingEvent.Milage;
       existingEvent.SocialSecurityNumber = bookingEvent.SocialSecurityNumber;
       return existingEvent;
    });

    return bookingEvent;
 }

 public void Delete(BookingEventDAO bookingEvent)
 {
    // TODO
    throw new NotImplementedException();
 }

 public IEnumerable<BookingEventDAO> GetAll()
 {
    return _bookingEvents.Values;
 }
}

Read Full Post »