.NET Entity Framework Core Generic Async Operations With Unit Of Work Generic Repository

Entity Framework

Introduction

In this session, we will learn about:

  • Creating Generic Repository with Entity Framework.
  • Taking advantage of .NET generics
  • Creating ASP.NET Core custom API controller CRUD operations with AJAX calls.
  • Consuming Entity Framework Core 2.0, in-memory database.
  • Interface 
  • Class
  • Generic
  • async/await
  • DataContext 
  • Overriding onModelCreating
  • Overriding SaveChanges
  • Overriding Update
  • Overriding UpdateAsync
  • Overriding SaveChangesAsync
  • Creating audit structure
  • Dispose
  • Creating Abstract class
  • Getting WindowsIdentity Current User 
  • Creating a new insert item
  • Updating an Item
  • Deleting an Item 
  • Writing HttpPost Create API method.
  • Writing HttpPut Update API method.
  • Writing HttpPost Delete API method.
  • Route table
  • Setting start controller Route to Home Index method.
  • jQuery/HTML pass table row value to a JavaScript function
  • jQuery Ajax HttpGet
  • jQuery Ajax HttpPut
  • jQuery Ajax HttpPost
  • Editable HTML table 

Advantage of generic repository is that you can inherit from it, pass an entity type, and you will have CRUD operations. It will save you a lot of coding time when your domain objects are likely to grow over 50+. Another advantage is a change history functionality; you can inherit your entities from change history interface and you have the functionality.

The repository pattern creates an abstract layer between the Data Access Layer and the Service Layer of an application.

Entity Framework

There is more than one way to implement the unit of work and repository patterns. You need to pick which one works best for your project specific needs.

Entity Framework is an object-relational mapper(ORM), which enables the developer to work with relational data using domain-specific object and allows the use of LINQ or Lambda expressions to search or filer data in the database.

NOTE

Our generic repository is not bullet proof with all the functionalities but rather flexible enough that you can easily extend per your own needs.

Pre-Requirements

To be able to run the example from the download or build it from scratch, you need to have the following tools,

  • Visual Studio 2017 or above 
  • .NET Core 2.0 or above

Generic repository Interface and Generic repository abstract class

GenericRepository<T> : IGenericRepository<T> where T : class
Entity Framework
We start with EF action methods and put them in a generic repository interface IGenericRepository.

  1. //Copyright 2017 (c) SmartIT. All rights reserved. By John Kocer  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Linq.Expressions;  
  6. using System.Threading.Tasks;  
  7.   
  8. namespace EfCoreGenericRepository.DataAccess  
  9. {  
  10.   public interface IGenericRepository<T> where T : class  
  11.   {  
  12.     T Add(T t);  
  13.     Task<T> AddAsyn(T t);  
  14.     int Count();  
  15.     Task<int> CountAsync();  
  16.     void Delete(T entity);  
  17.     Task<int> DeleteAsyn(T entity);  
  18.     void Dispose();  
  19.     T Find(Expression<Func<T, bool>> match);  
  20.     ICollection<T> FindAll(Expression<Func<T, bool>> match);  
  21.     Task<ICollection<T>> FindAllAsync(Expression<Func<T, bool>> match);  
  22.     Task<T> FindAsync(Expression<Func<T, bool>> match);  
  23.     IQueryable<T> FindBy(Expression<Func<T, bool>> predicate);  
  24.     Task<ICollection<T>> FindByAsyn(Expression<Func<T, bool>> predicate);  
  25.     T Get(int id);  
  26.     IQueryable<T> GetAll();  
  27.     Task<ICollection<T>> GetAllAsyn();  
  28.     IQueryable<T> GetAllIncluding(params Expression<Func<T, object>>[] includeProperties);  
  29.     Task<T> GetAsync(int id);  
  30.     void Save();  
  31.     Task<int> SaveAsync();  
  32.     T Update(T t, object key);  
  33.     Task<T> UpdateAsyn(T t, object key);  
  34.   }  
  35. }  

We implement GenericRepository with Generic T. You can add your future methods here. We added dispose method which can be called on the Controller’s override of the dispose method.

  1. //Copyright 2017 (c) SmartIT. All rights reserved. By John Kocer  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Linq.Expressions;  
  6. using System.Threading.Tasks;  
  7. using Microsoft.EntityFrameworkCore;  
  8.   
  9. namespace EfCoreGenericRepository.DataAccess  
  10. {  
  11.   public abstract class GenericRepository<T> : IGenericRepository<T> where T : class  
  12.   {  
  13.     protected DataContext _context;  
  14.   
  15.     public GenericRepository(DataContext context)  
  16.     {  
  17.       _context = context;  
  18.     }  
  19.   
  20.     public IQueryable<T> GetAll()  
  21.     {  
  22.       return _context.Set<T>();  
  23.     }  
  24.   
  25.     public virtual async Task<ICollection<T>> GetAllAsyn()  
  26.     {  
  27.   
  28.       return await _context.Set<T>().ToListAsync();  
  29.     }  
  30.   
  31.     public virtual T Get(int id)  
  32.     {  
  33.       return _context.Set<T>().Find(id);  
  34.     }  
  35.   
  36.     public virtual async Task<T> GetAsync(int id)  
  37.     {  
  38.       return await _context.Set<T>().FindAsync(id);  
  39.     }  
  40.   
  41.     public virtual T Add(T t)  
  42.     {  
  43.   
  44.       _context.Set<T>().Add(t);  
  45.       _context.SaveChanges();  
  46.       return t;  
  47.     }  
  48.   
  49.     public virtual async Task<T> AddAsyn(T t)  
  50.     {  
  51.       _context.Set<T>().Add(t);  
  52.       await _context.SaveChangesAsync();  
  53.       return t;  
  54.   
  55.     }  
  56.   
  57.     public virtual T Find(Expression<Func<T, bool>> match)  
  58.     {  
  59.       return _context.Set<T>().SingleOrDefault(match);  
  60.     }  
  61.   
  62.     public virtual async Task<T> FindAsync(Expression<Func<T, bool>> match)  
  63.     {  
  64.       return await _context.Set<T>().SingleOrDefaultAsync(match);  
  65.     }  
  66.   
  67.     public ICollection<T> FindAll(Expression<Func<T, bool>> match)  
  68.     {  
  69.       return _context.Set<T>().Where(match).ToList();  
  70.     }  
  71.   
  72.     public async Task<ICollection<T>> FindAllAsync(Expression<Func<T, bool>> match)  
  73.     {  
  74.       return await _context.Set<T>().Where(match).ToListAsync();  
  75.     }  
  76.   
  77.     public virtual void Delete(T entity)  
  78.     {  
  79.       _context.Set<T>().Remove(entity);  
  80.       _context.SaveChanges();  
  81.     }  
  82.   
  83.     public virtual async Task<int> DeleteAsyn(T entity)  
  84.     {  
  85.       _context.Set<T>().Remove(entity);  
  86.       return await _context.SaveChangesAsync();  
  87.     }  
  88.   
  89.     public virtual T Update(T t, object key)  
  90.     {  
  91.       if (t == null)  
  92.         return null;  
  93.       T exist = _context.Set<T>().Find(key);  
  94.       if (exist != null) {   
  95.         _context.Entry(exist).CurrentValues.SetValues(t);  
  96.         _context.SaveChanges();  
  97.       }  
  98.       return exist;  
  99.     }  
  100.   
  101.     public virtual async Task<T> UpdateAsyn(T t, object key)  
  102.     {  
  103.       if (t == null)  
  104.         return null;  
  105.       T exist =await  _context.Set<T>().FindAsync(key);  
  106.       if (exist != null)  
  107.       {  
  108.         _context.Entry(exist).CurrentValues.SetValues(t);  
  109.         await _context.SaveChangesAsync();  
  110.       }  
  111.       return exist;  
  112.     }  
  113.   
  114.     public int Count()  
  115.     {  
  116.       return _context.Set<T>().Count();  
  117.     }  
  118.   
  119.     public async Task<int> CountAsync()  
  120.     {  
  121.       return await _context.Set<T>().CountAsync();  
  122.     }  
  123.   
  124.     public virtual void Save()  
  125.     {  
  126.   
  127.       _context.SaveChanges();  
  128.     }  
  129.   
  130.     public async virtual Task<int> SaveAsync()  
  131.     {  
  132.       return await _context.SaveChangesAsync();  
  133.     }  
  134.   
  135.     public virtual IQueryable<T> FindBy(Expression<Func<T, bool>> predicate)  
  136.     {  
  137.       IQueryable<T> query = _context.Set<T>().Where(predicate);  
  138.       return query;  
  139.     }  
  140.   
  141.     public virtual async Task<ICollection<T>> FindByAsyn(Expression<Func<T, bool>> predicate)  
  142.     {  
  143.       return await _context.Set<T>().Where(predicate).ToListAsync();  
  144.     }  
  145.   
  146.     public IQueryable<T> GetAllIncluding(params Expression<Func<T, object>>[] includeProperties)  
  147.     {  
  148.   
  149.       IQueryable<T> queryable = GetAll();  
  150.       foreach (Expression<Func<T, object>> includeProperty in includeProperties)  
  151.       {  
  152.   
  153.         queryable = queryable.Include<T, object>(includeProperty);  
  154.       }  
  155.   
  156.       return queryable;  
  157.     }  
  158.   
  159.     private bool disposed = false;  
  160.     protected virtual void Dispose(bool disposing)  
  161.     {  
  162.       if (!this.disposed)  
  163.       {  
  164.         if (disposing)  
  165.         {  
  166.           _context.Dispose();  
  167.         }  
  168.         this.disposed = true;  
  169.       }  
  170.     }  
  171.   
  172.     public void Dispose()  
  173.     {  
  174.       Dispose(true);  
  175.       GC.SuppressFinalize(this);  
  176.     }  
  177.   }  
  178. }  

Custom entity interface inherits from generic repository interface

IBlogRepository : IGenericRepository<Blog>

If you need any specific action for an entity such as id type we can put it here.

  1. using EfCoreGenericRepository.Models;  
  2.   
  3. namespace EfCoreGenericRepository.DataAccess  
  4. {  
  5.   public interface IBlogRepository : IGenericRepository<Blog>  
  6.     {  
  7.         // If you need to customize your entity actions you can put here    
  8.         Blog Get(int blogId);  
  9.     }  
  10. }  
Custom entity CRUD operation can be accomplish inheriting from

GenericRepository<Blog>, IBlogRepository

Entity Framework

BlogRepository inherits from abstract class GenericRepository and Interface IBlogRepository. We override Update and UpdateAsync methods because CreateBy and CreatedOn values do not need to be changed after initial creation.
  1. //Copyright 2017 (c) SmartIT. All rights reserved. By John Kocer  
  2. using System.Linq;  
  3. using System.Threading.Tasks;  
  4. using EfCoreGenericRepository.Models;  
  5.   
  6. namespace EfCoreGenericRepository.DataAccess  
  7. {  
  8.   public class BlogRepository : GenericRepository<Blog>, IBlogRepository  
  9.   {  
  10.   
  11.     public BlogRepository(DataContext context) : base(context)  
  12.     {  
  13.     }  
  14.   
  15.     public Blog Get(int blogId)  
  16.     {  
  17.       var query = GetAll().FirstOrDefault(b => b.BlogId == blogId);  
  18.       return query;  
  19.     }  
  20.   
  21.     public async Task<Blog> GetSingleAsyn(int blogId)  
  22.     {  
  23.       return await _context.Set<Blog>().FindAsync(blogId);  
  24.     }  
  25.   
  26.     public override Blog Update(Blog t, object key)  
  27.     {  
  28.       Blog exist = _context.Set<Blog>().Find(key);  
  29.       if (exist != null)  
  30.       {  
  31.         t.CreatedBy = exist.CreatedBy;  
  32.         t.CreatedOn = exist.CreatedOn;  
  33.       }  
  34.       return base.Update(t, key);  
  35.     }  
  36.   
  37.     public async override Task<Blog> UpdateAsyn(Blog t, object key)  
  38.     {  
  39.       Blog exist =await  _context.Set<Blog>().FindAsync(key);  
  40.       if (exist != null)  
  41.       {  
  42.         t.CreatedBy = exist.CreatedBy;  
  43.         t.CreatedOn = exist.CreatedOn;  
  44.       }  
  45.       return await base.UpdateAsyn(t, key);  
  46.     }  
  47.   }  
  48. }  
Change Tracking with inheritance

IAuditable 

Change tracking for audit purposes can be accomplished using IAudible. Any entity that needs to be change tracked inherits from IAudible interface. We override DataContext class SaveChanges and SaveChangesAsync methods to get CreatedBy, CreatedOn, UpdatedBy and UpdatedOn values.

  1. using System;  
  2.   
  3. namespace EfCoreGenericRepository.Models  
  4. {  
  5.   public interface IAuditable  
  6.     {  
  7.         string CreatedBy { get; set; }  
  8.         DateTime? CreatedOn { get; set; }  
  9.         string UpdatedBy { get; set; }  
  10.         DateTime? UpdatedOn { get; set; }  
  11.     }  
  12. }  

Blog entity inherits from IAudiable to have change tracking member implemented.

  1. //Copyright 2017 (c) SmartIT. All rights reserved. By John Kocer  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.ComponentModel.DataAnnotations;  
  5.   
  6. namespace EfCoreGenericRepository.Models  
  7. {  
  8.   public class Blog:IAuditable  
  9.     {  
  10.         [Key]  
  11.         public int BlogId { get; set; }  
  12.         public string Title { get; set; }  
  13.         public ICollection<Post> Posts { get; set; }=new HashSet<Post>();  
  14.         public string CreatedBy { get; set; }  
  15.   
  16.         public DateTime? CreatedOn { get; set; }  
  17.         public string UpdatedBy { get; set; }  
  18.         public DateTime? UpdatedOn { get; set; }  
  19.     }  
  20. }  
DataContext class

DataContect class inherits from EF DbCotext class as we can see from below inheritance diagram.
Entity Framework
DataContect class has DataSet, overridden SaveChanges and SaveChangesAsync method, and UserProvider property to get current user in windows system, and TimeStampProvider to add Created and updated times. You can convert time to Universal Time (UTC) if you need to.
  1. //Copyright 2017 (c) SmartIT. All rights reserved. By John Kocer  
  2. using System;  
  3. using System.Linq;  
  4. using System.Security.Principal;  
  5. using System.Threading;  
  6. using System.Threading.Tasks;  
  7. using Microsoft.EntityFrameworkCore;  
  8. using EfCoreGenericRepository.Models;  
  9.   
  10. namespace EfCoreGenericRepository.DataAccess  
  11. {  
  12.   public class DataContext : DbContext  
  13.   {  
  14.     public DataContext(DbContextOptions<DataContext> options) : base(options){}  
  15.   
  16.     protected override void OnModelCreating(ModelBuilder builder)  
  17.     {  
  18.       builder.Entity<Post>()  
  19.           .HasOne(b => b.Blog)  
  20.           .WithMany(p => p.Posts)  
  21.           .IsRequired();  
  22.       base.OnModelCreating(builder);  
  23.     }  
  24.   
  25.     public virtual void Save()  
  26.     {  
  27.       base.SaveChanges();  
  28.     }  
  29.     public string UserProvider  
  30.     {  
  31.       get  
  32.       {  
  33.         if (!string.IsNullOrEmpty(WindowsIdentity.GetCurrent().Name))  
  34.           return WindowsIdentity.GetCurrent().Name.Split('\\')[1];  
  35.         return string.Empty;  
  36.       }  
  37.     }  
  38.   
  39.     public Func<DateTime> TimestampProvider { get; set; } = ()  
  40.         => DateTime.UtcNow;  
  41.     public override int SaveChanges()  
  42.     {  
  43.       TrackChanges();  
  44.       return base.SaveChanges();  
  45.     }  
  46.       
  47.     public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())  
  48.     {  
  49.       TrackChanges();  
  50.       return await base.SaveChangesAsync(cancellationToken);  
  51.     }  
  52.   
  53.     private void TrackChanges()  
  54.     {  
  55.       foreach (var entry in this.ChangeTracker.Entries().Where(e => e.State == EntityState.Added || e.State == EntityState.Modified))  
  56.       {  
  57.         if (entry.Entity is IAuditable)  
  58.         {  
  59.           var auditable = entry.Entity as IAuditable;  
  60.           if (entry.State == EntityState.Added)  
  61.           {  
  62.             auditable.CreatedBy = UserProvider;//  
  63.             auditable.CreatedOn = TimestampProvider();  
  64.             auditable.UpdatedOn = TimestampProvider();  
  65.           }  
  66.           else  
  67.           {  
  68.             auditable.UpdatedBy = UserProvider;  
  69.             auditable.UpdatedOn = TimestampProvider();  
  70.           }  
  71.         }  
  72.       }  
  73.     }  
  74.   
  75.     public DbSet<Blog> Blog { get; set; }  
  76.     public DbSet<BlogDetail> BlogDetail { get; set; }  
  77.     public DbSet<Post> Post { get; set; }  
  78.   }  
  79. }  
Consuming the Generic Repository class

API Controller, MVC Controller or Service layer.

On WebAPI controller we have repository specific Database calls through our generic repository. It is a good idea to have service layer between repository and API controller.

We dispose the Context object here calling overridden dispose method.

  1. //Copyright 2017 (c) SmartIT. All rights reserved. By John Kocer  
  2. using Microsoft.AspNetCore.Mvc;  
  3. using System.Collections.Generic;  
  4. using System.Threading.Tasks;  
  5. using EfCoreGenericRepository.DataAccess;  
  6.   
  7. namespace Blog.Ui.Controllers  
  8. {  
  9.   [Produces("application/json")]  
  10.   [Route("api/Blog")]  
  11.   public class BlogsApiController : Controller  
  12.   {  
  13.     private readonly IBlogRepository _blogRepository;  
  14.   
  15.     public BlogsApiController(IBlogRepository blogRepository)  
  16.     {  
  17.       _blogRepository = blogRepository;  
  18.   
  19.     }  
  20.   
  21.     [Route("~/api/GetBlogs")]  
  22.     [HttpGet]  
  23.     public async Task<IEnumerable<EfCoreGenericRepository.Models.Blog>> Index()  
  24.     {  
  25.       return await _blogRepository.GetAllAsyn();  
  26.     }  
  27.   
  28.     [Route("~/api/AddBlog")]  
  29.     [HttpPost]  
  30.     public async Task<EfCoreGenericRepository.Models.Blog> AddBlog([FromBody]EfCoreGenericRepository.Models.Blog blog)  
  31.     {  
  32.         await _blogRepository.AddAsyn(blog);  
  33.         await _blogRepository.SaveAsync();  
  34.       return blog;  
  35.     }  
  36.   
  37.     [Route("~/api/UpdateBlog")]  
  38.     [HttpPut]  
  39.     //public Blog UpdateBlog([FromBody] Blog blog)  
  40.     //{  
  41.     //  var updated = _blogRepository.Update(blog, blog.BlogId);  
  42.     //  return updated;  
  43.     //}  
  44.     public async Task<EfCoreGenericRepository.Models.Blog> UpdateBlog([FromBody]EfCoreGenericRepository.Models.Blog blog)  
  45.     {  
  46.       var updated =await  _blogRepository.UpdateAsyn(blog, blog.BlogId);  
  47.       return updated;  
  48.     }  
  49.   
  50.     [Route("~/api/DeleteBlog/{id}")]  
  51.     [HttpDelete]  
  52.     public string Delete(int id)  
  53.     {  
  54.       _blogRepository.Delete(_blogRepository.Get(id));  
  55.       return "Employee deleted successfully!";  
  56.     }  
  57.   
  58.     protected override void Dispose(bool disposing)  
  59.     {  
  60.       _blogRepository.Dispose();  
  61.       base.Dispose(disposing);  
  62.     }  
  63.   }  
  64. }  
Dependency Injection

We add generic repository dependency injection in the Startup configure services method.

  1. //in the Startup.cs  
  2. public void ConfigureServices(IServiceCollection services)  
  3.     {  
  4.       services.AddMvc();  
  5.       services.AddDbContext<DataContext>(options =>  
  6.          options.UseInMemoryDatabase());  
  7.       services.AddTransient<IBlogRepository, BlogRepository>();  
  8.     }  

 When we run our demo application, we will see the below page which does Blog CRUD operations using our generic repository.

Entity Framework

Summary

In this article, we have learned how to write generic repository pattern. In Part 2, we will learn repository and Unit of work pattern implementation. 

Tasks leaned from this article,

  • Creating Generic Repository with Entity Framework.
  • Taking advantage of .NET generics
  • Creating ASP.NET Core custom API controller CRUD operations with AJAX calls.
  • Consuming Entity Framework Core 2.0, in-memory database.
  • Interface 
  • Class
  • Generic
  • async/await
  • DataContext 
  • Overriding onModelCreating
  • Overriding SaveChanges
  • Overriding Update
  • Overriding UpdateAsync
  • Overriding SaveChangesAsync
  • Creating audit structure
  • Dispose
  • Creating Abstract class
  • Getting WindowsIdentity Current User 
  • Creating a new insert item
  • Updating an Item
  • Deleting an Item 
  • Writing HttpPost Create API method.
  • Writing HttpPut Update API method.
  • Writing HttpPost Delete API method.
  • Route table
  • Setting start controller Route to Home Index method.
  • jQuery/HTML pass table row value to a JavaScript function
  • jQuery Ajax HttpGet
  • jQuery Ajax HttpPut
  • jQuery Ajax HttpPost
  • Editable HTML table 

Download source code from GitHub.

 


Similar Articles