Shopping Cart Application Part-09 (Repository classes)

By | April 13, 2015

@. Now we’ll create base repository class that will implement IRepository interface (that we defined inside Shoppingcart.Infrastructure layer).
@. Let’s add a class and named it Repository with following definition:

public abstract class Repository : IRepository where T : BaseEntity, IAggregateRoot
{
    private ShoppingcartContext dataContext;
    private readonly DbSet dbset;
    protected Repository(IDataContextFactory dataContextFactory)
    {
        DataContextFactory = dataContextFactory;
        dbset = DataContext.Set();
    }

    protected IDataContextFactory DataContextFactory
    {
        get;
        private set;
    }

    protected ShoppingcartContext DataContext
    {
        get { return dataContext ?? (dataContext = DataContextFactory.Get()); }
    }

    public virtual void Save(T entity)
    {
        dbset.Add(entity);
    }
    public virtual void Update(T entity)
    {
        dbset.Attach(entity);
        dataContext.Entry(entity).State = EntityState.Modified;
    }
    public virtual void Delete(T entity)
    {
        dbset.Remove(entity);
    }
    public virtual void Delete(Expression> where)
    {
        IEnumerable objects = dbset.Where(where).AsEnumerable();
        foreach (T obj in objects)
            dbset.Remove(obj);
    }
    public virtual T GetById(TId id)
    {
        return dbset.Find(id);
    }
    public virtual IEnumerable GetAll()
    {
        return dbset.ToList();
    }
    public virtual IEnumerable GetMany(Expression> where)
    {
        return dbset.Where(where).ToList();
    }
    public T Get(Expression> where)
    {
        return dbset.Where(where).FirstOrDefault();
    }

    //Stored Procedure
    public IEnumerable ExecWithStoreProcedure(string query)
    {
        return DataContext.Database.SqlQuery(query);
    }

    public void ExecuteWithStoreProcedure(string query, params object[] parameters)
    {
        DataContext.Database.ExecuteSqlCommand(query, parameters);
    }

    //Async 

    public virtual async Task GetByIdAsync(TId id)
    {
        return await dbset.FindAsync(id);
    }
    public virtual async Task> GetAllAsync()
    {
        return await dbset.ToListAsync();
    }
    public virtual async Task> GetManyAsync(Expression> where)
    {
        return await dbset.Where(where).ToListAsync();
    }
    public async Task GetAsync(Expression> where)
    {
        return await dbset.Where(where).FirstOrDefaultAsync();
    }

    //Stored Procedure Async
    public async Task> ExecWithStoreProcedureAsync(string query, params object[] parameters)
    {
        return await DataContext.Database.SqlQuery(query, parameters).ToListAsync();
    }

    public async Task ExecuteWithStoreProcedureAsync(string query, params object[] parameters)
    {
        await DataContext.Database.ExecuteSqlCommandAsync(query, parameters);
    }

}

@. Above class is an abstract class.
@. It is also a generic class where T indicates those classes that inherit BaseEntity, IAggregateRoot.
@. All the methods inside above class also generic.
@. Though this class is generic so, we will be able to provide all functionalities for all repositories.

@. Inside above class we created different methods for add, attach, remove and get data from/to DbSet.
@. DbSet class represents an entity set that is used for the create, read, update, and delete operations. Inside above class we used the generic version of this class i.e. DbSet because our repository class is also generic.
@. DbSet objects are created from DbContext using DbContext.Set method.
@. In our repository class we created DbSet object inside constructor by using DataContext.Set method.

@. Inside our repository class the DataContext has read-only property that get new instance from DataContext factory when it remain null.

@. DataContextFactory is a property with getter and private setter method and it initialized inside constructor through constructor injection.

@. We also defined methods for execute stored procedures and execute queries inside above repository class.

@. As above class is an abstract class, so it will not be possible to instantiate this class. We will use it as base class.
@. So we have to create individual repository for each domain model of Product Catalog that’s are also AggregateRoot i.e. – Category, ProductTitle and Product domain models
@. Let’s create repository classes for above models.

CategoryRepository
@. Now we’ll create a repository for Category domain model that will implemented Repository class and ICategoryRepository as follows:

public class CategoryRepository:Repository,ICategoryRepository
{
     public CategoryRepository(IDataContextFactory factory) : base(factory) 
     {

     }
}

Note:
+. During inheriting Repository class we passed Category domain model as it’s type parameter, so it will serve all the purposes of Category repository. Same will happen for ProductTitle and Product repositories.
+. Though Repository class already implemented IRepository interface and IRepository inherited IReadOnlyRepository, so we don’t need further implement ICategoryRepository because ICategoryRepository inherited IReadOnlyRepository.

ProductTitleRepository
@. Now we’ll create a repository for ProductTitle domain model that will implemented Repository class and IProductTitleRepository as follows:

public class ProductTitleRepository:Repository,IProductTitleRepository
{
     public ProductTitleRepository(IDataContextFactory factory): base(factory) 
     {

     }
}

ProductRepository
@. Now we’ll create a repository for Product domain model that will implemented Repository class and IProductRepository as follows:

public class ProductRepository:Repository,IProductRepository
{
     public ProductRepository(IDataContextFactory factory): base(factory) 
     {

     }
}

One can download entire source from here

637 Total Views 1 Views Today
Md. Mojammel Haque

CSM, CSPO, CSD, CSP-SM, CSP-PO (ScrumAlliance.org)
Certification Profile Link-
https://www.scrumalliance.org/community/profile/mhaque13

Currently working as Lead Team (Application Architecture) at Raven Systems Ltd. Passion for software development especially agile practices such as TDD with in depth knowledge of Object Oriented Programming, SOLID Principles, Gang of Four Design Patterns, Some Enterprise Application Architectural Patterns. Over 8 years of software development experience ASP.NET. Has the ability to understand and transform complex business requirements into software ensuring applications are delivered on time. Also experience in non Microsoft .NET technologies such as Dapper.Net, Git, Structure Map & Angular, Bootstrap, HTML-5, CSS-3 etc.

Category: 1.10-Asp.net MVC Learn by doing - ASP.Net MVC Uncategorized
Md. Mojammel Haque

About Md. Mojammel Haque

CSM, CSPO, CSD, CSP-SM, CSP-PO (ScrumAlliance.org) Certification Profile Link- https://www.scrumalliance.org/community/profile/mhaque13 Currently working as Lead Team (Application Architecture) at Raven Systems Ltd. Passion for software development especially agile practices such as TDD with in depth knowledge of Object Oriented Programming, SOLID Principles, Gang of Four Design Patterns, Some Enterprise Application Architectural Patterns. Over 8 years of software development experience ASP.NET. Has the ability to understand and transform complex business requirements into software ensuring applications are delivered on time. Also experience in non Microsoft .NET technologies such as Dapper.Net, Git, Structure Map & Angular, Bootstrap, HTML-5, CSS-3 etc.

Leave a Reply

Your email address will not be published. Required fields are marked *