Generic DataAcsessLayer using C#


Generic DataAcsessLayer is highly architect which will be helpful to create DAL layer for any type of project. The Basic CRUD operations are defined in an Interface and all the classes are interacting through an Interface and DAL layer classes are Internal so that it will not be exposed outside of that assembly. 

public interface IDbService<T, TKey> where T : IEntity
{
    IList<T> GetAll();
    T GetById(TKey key);
    bool Update(T entity, TKey key);
    int Add(T entity);
}

IDbService is a Generic Interface which you can pass any type of class like. Customer, Product etc as T and Tkey defines your Identification Key. It might be long, int or double as per the requirement.

public interface ICustomerService : IDbService<Customer, int>
{
    IList<Customer> GetCustomersByDeptID(int departmentId);
}

ICustomerService which implements IDbService having extend functionality GetCustomersByDeptID() Which is only for Customer not for Product.

Now Customer.cs will implement ICustomerService

internal class CustomerService : ICustomerService
{
    private readonly DataAccess _db;
    private readonly IFactory<Customer> _factory;
    private const string UspSelGetcustomers = "GetCustomers";
    private const string UspSelGetcustomerById = "GetCustomers";
    private const string UspSelGetcustomerByDeptId = "GetCustomers";
    private const string UspInsCustomer = "GetCustomers";
    private const string UspUpdCustomer = "GetCustomers";

    public CustomerService(DataAccess db, IFactory<Customer> factory)
    {
        _db = db;
        _factory = factory;
    }

    public IList<Customer> GetAll()
    {
        return _factory.CreateList(_db.ExecuteReader(UspSelGetcustomers));
    }

    public Customer GetById(int key)
    {
        return _factory.Create(_db.ExecuteReader("GetCustomerById", key));
    }

    public bool Update(Customer entity, int key)
    {
        throw new NotImplementedException();
    }

    public int Add(Customer entity)
    {
        throw new NotImplementedException();
    }

    public IList<Customer> GetByDepartment(int departmentId)
    {
        throw new NotImplementedException();
    }
}

Please find the Source code and Class diagram for better understanding.

ClassDiagram1.jpg  


Recommended Free Ebook
Similar Articles