Return types for methods in Repository pattern

We are using repository pattern, but we wanted the repository methods to return more than what the official methods return. We needed it to return the following additional data.

  1. Number of Records affected.
  2. Errors raised by the database that needs to be passed to the user.
  3. A Boolean value specifying whether the transaction was successful or not.

And may be some more values in the future. So we created the following generic class which will be the return type for all the Repository Classes

  1. public class RepositoryReturnType<T>  
  2. {  
  3.     private List<T> returnList;  
  4.     public IList<T> ReturnList  
  5.     {  
  6.         get  
  7.         {  
  8.             return returnList;  
  9.         }  
  10.     }  
  11.   
  12.     public void WriteReturnList(List<T> t)  
  13.     {  
  14.         returnList = t;  
  15.     }  
  16.   
  17.     public T ReturnData { getset; }  
  18.     public string Message { getset; }  
  19.     public int RecordsAffected { getset; }  
  20.     public bool IsTransactionSuccess { getset; }  

(For those wondering why there is no setter in the ReturnList, refer to this link https://goo.gl/jReCPN)
 
So this is how the signature of the repository methods will look like.
  1. public interface ISchoolRepository  
  2. {  
  3.     RepositoryReturnType<Student> StudentsList {get;}  
  4.     RepositoryReturnType<Student> Add(Student student);  
  5.     RepositoryReturnType<Student> Find(int Id);  

And when this interface is implemented, this is how it will look like,
  1. public RepositoryReturnType<Student> Create(Student student)  
  2.         {  
  3.             int RecordsAffected = 0;  
  4.             string Message;  
  5.             using (var context = new SomeEntities())  
  6.             {  
  7.                 try  
  8.                 {  
  9.                     context.Student.AddObject(student);  
  10.                     RecordsAffected = context.SaveChanges();  
  11.                     Message = "Record Created Successfully";  
  12.                 }  
  13.                 catch (Exception Exception)  
  14.                 {  
  15.                     //This method will return Error Message if the users needs to know about it,   
  16.                     //For example exception about duplicate record created  
  17.                     Message = Utilities.RepositoryMessage(Exception);  
  18.                 }  
  19.                 finally  
  20.                 {  
  21.                     context.Connection.Close();  
  22.                 }  
  23.             }  
  24.             return new RepositoryReturnType<Student>() { RecordsAffected = RecordsAffected, Message = Message };  
  25.         }  
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now