Skip to content

Developing Infrastructure Layer

Mehmet Özkaya edited this page Mar 25, 2019 · 1 revision

Developing Infrastructure Layer

When we finished to Core layer operations its good to continue with Infrastructure Layer in order to implement interfaces. So the above section we were defined custom repository interfaces, so in this layer we should implement them.

Its not mandatory to create and implement repository classes, IAsyncRepository and its implementation class AspnetRunRepository.cs is cover all crud operations. So if you have custom database requirements than you should choose this way.

public class ProductRepository : AspnetRunRepository<Product>, IProductRepository
    {
        public ProductRepository(AspnetRunContext dbContext) : base(dbContext)
        {
        }

        public async Task<IEnumerable<Product>> GetProductListAsync()
        {
            // return await GetAllAsync();

            var spec = new ProductWithCategorySpecification();
            return await GetAsync(spec);
        }

        public async Task<IEnumerable<Product>> GetProductByNameAsync(string productName)
        {
            var spec = new ProductWithCategorySpecification(productName);
            return await GetAsync(spec);
        }
        
        public async Task<IEnumerable<Product>> GetProductByCategoryAsync(int categoryId)
        {
            return await _dbContext.Products
                .Where(x => x.CategoryId==categoryId)
                .ToListAsync();
        }
    }

public class CategoryRepository : AspnetRunRepository<Category>, ICategoryRepository
    {
        public CategoryRepository(AspnetRunContext dbContext) : base(dbContext)
        {            
        }

        public async Task<Category> GetCategoryWithProductsAsync(int categoryId)
        {            
            var spec = new CategoryWithProductsSpecification(categoryId);
            var category = (await GetAsync(spec)).FirstOrDefault();
            return category;
        }
    }

As you can see that these implementation classes inherit from AspnetRunRepository.cs in order to use Entity Framework Core dbContext object and use benefits from db abstractions.

Product-Category Add to Context

We were choosing code-first approach of Entity Framework Core so we should add entities into Entity Framework Core Context object in order to reflect database.

public class AspnetRunContext : DbContext
{     
        public DbSet<Product> Products { get; set; }
        public DbSet<Category> Categories { get; set; }
}

At above, we added database sets of entity objects into our Entity Framework Core context. By this way we can navigate this entities with InMemory and Read Sql Server databases.

Clone this wiki locally