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.
- Number of Records affected.
- Errors raised by the database that needs to be passed to the user.
- 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
- public class RepositoryReturnType<T>
- {
- private List<T> returnList;
- public IList<T> ReturnList
- {
- get
- {
- return returnList;
- }
- }
-
- public void WriteReturnList(List<T> t)
- {
- returnList = t;
- }
-
- public T ReturnData { get; set; }
- public string Message { get; set; }
- public int RecordsAffected { get; set; }
- public bool IsTransactionSuccess { get; set; }
- }
(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.
- public interface ISchoolRepository
- {
- RepositoryReturnType<Student> StudentsList {get;}
- RepositoryReturnType<Student> Add(Student student);
- RepositoryReturnType<Student> Find(int Id);
- }
And when this interface is implemented, this is how it will look like,
- public RepositoryReturnType<Student> Create(Student student)
- {
- int RecordsAffected = 0;
- string Message;
- using (var context = new SomeEntities())
- {
- try
- {
- context.Student.AddObject(student);
- RecordsAffected = context.SaveChanges();
- Message = "Record Created Successfully";
- }
- catch (Exception Exception)
- {
-
-
- Message = Utilities.RepositoryMessage(Exception);
- }
- finally
- {
- context.Connection.Close();
- }
- }
- return new RepositoryReturnType<Student>() { RecordsAffected = RecordsAffected, Message = Message };
- }