Thursday, 6 February 2014

Repository Pattern Implementation with Entiry Framework

IRepository.cs
interface IRepository<T> : IDisposable where T : class
    {
        /// <summary>
        /// Gets all records as an IEnumerable
        /// </summary>
        /// <returns>An IQueryable object containing the results of the query</returns>
        IEnumerable<T> Fetch();

        /// <summary>
        /// Finds a record with the specified criteria
        /// </summary>
        /// <param name="predicate">Criteria to match on</param>
        /// <returns>A collection containing the results of the query</returns>
        IEnumerable<T> Find(Func<T, bool> predicate);

        /// <summary>
        /// Gets a single record by the specified criteria (usually the unique identifier)
        /// </summary>
        /// <param name="predicate">Criteria to match on</param>
        /// <returns>A single record that matches the specified criteria</returns>
        T Single(Func<T, bool> predicate);

        /// <summary>
        /// The first record matching the specified criteria
        /// </summary>
        /// <param name="predicate">Criteria to match on</param>
        /// <returns>A single record containing the first record matching the specified criteria</returns>
        T First(Func<T, bool> predicate);

        /// <summary>
        /// Adds the specified entity
        /// </summary>
        /// <param name="entity">Entity to add</param>
        /// <exception cref="ArgumentNullException"> if <paramref name="entity"/> is null</exception>
        void Add(T entity);

        /// <summary>
        /// Deletes the specified entitiy       
        /// </summary>
        /// <param name="entity">Entity to delete</param>
        /// <exception cref="ArgumentNullException"> if <paramref name="entity"/> is null</exception>
        void Delete(T entity);

        /// <summary>
        /// Attaches the specified entity        
        /// </summary>
        /// <param name="entity">Entity to attach</param>
        void Attach(T entity);

        /// <summary>
        /// Saves all context changes       
        /// </summary>
        void SaveChanges();

        /// <summary>
        /// Saves all context changes with the specified SaveOptions       
        /// </summary>
        /// <param name="options">Options for saving the context</param>
        void SaveChanges(SaveOptions options);
    }


DataRepository.cs
/// <summary>
    /// A generic repository for working with data in the database
    /// </summary>
    /// <typeparam name="T">A POCO that represents an Entity Framework entity</typeparam>
    public class DataRepository<T> : IRepository<T> where T : class
    {
        /// <summary>
        /// The context object for the database       
        /// </summary>
        public ObjectContext Context { get; private set; }

        /// <summary>
        /// The IObjectSet that represents the current entity.       
        /// </summary>
        public IObjectSet<T> ObjectSet { get; private set; }

        /// <summary>
        /// Initializes a new instance of the DataRepository class       
        /// </summary>
        /// <param name="context">The Entity Framework ObjectContext</param>
        public DataRepository(ObjectContext context)
        {
            this.Context = context;
            this.ObjectSet = this.Context.CreateObjectSet<T>();
        }

        /// <summary>
        /// Gets all records as an IEnumerable       
        /// </summary>
        /// <returns>An IQueryable object containing the results of the query</returns>
        public IEnumerable<T> Fetch()
        {
            return this.ObjectSet;
        }

        /// <summary>
        /// Finds a record with the specified criteria       
        /// </summary>
        /// <param name="predicate">Criteria to match on</param>
        /// <returns>A collection containing the results of the query</returns>
        public IEnumerable<T> Find(Func<T, bool> predicate)
        {
            return this.ObjectSet.Where<T>(predicate);
        }

        /// <summary>
        /// Gets a single record by the specified criteria (usually the unique identifier)       
        /// </summary>
        /// <param name="predicate">Criteria to match on</param>
        /// <returns>A single record that matches the specified criteria</returns>
        public T Single(Func<T, bool> predicate)
        {
            return this.ObjectSet.Single<T>(predicate);
        }

        /// <summary>
        /// The first record matching the specified criteria       
        /// </summary>
        /// <param name="predicate">Criteria to match on</param>
        /// <returns>A single record containing the first record matching the specified criteria</returns>
        public T First(Func<T, bool> predicate)
        {
            return this.ObjectSet.First<T>(predicate);
        }

        /// <summary>
        /// Deletes the specified entitiy       
        /// </summary>
        /// <param name="entity">Entity to delete</param>
        /// <exception cref="ArgumentNullException"> if <paramref name="entity"/> is null</exception>
        public void Delete(T entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            this.ObjectSet.DeleteObject(entity);
        }

        /// <summary>
        /// Deletes records matching the specified criteria       
        /// </summary>
        /// <param name="predicate">Criteria to match on</param>
        public void Delete(Func<T, bool> predicate)
        {
            IEnumerable<T> records = from x in this.ObjectSet.Where<T>(predicate) select x;

            foreach (T record in records)
            {
                this.ObjectSet.DeleteObject(record);
            }
        }

        /// <summary>
        /// Adds the specified entity        
        /// </summary>
        /// <param name="entity">Entity to add</param>
        /// <exception cref="ArgumentNullException"> if <paramref name="entity"/> is null</exception>
        public void Add(T entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            this.ObjectSet.AddObject(entity);
            SaveChanges();
        }

        /// <summary>
        /// Attaches the specified entity        
        /// </summary>
        /// <param name="entity">Entity to attach</param>
        public void Attach(T entity)
        {
            this.ObjectSet.Attach(entity);
        }

        /// <summary>
        /// Saves all context changes       
        /// </summary>
        public void SaveChanges()
        {
            this.Context.SaveChanges();
        }

        /// <summary>
        /// Saves all context changes with the specified SaveOptions        
        /// </summary>
        /// <param name="options">Options for saving the context</param>

        public void SaveChanges(SaveOptions options)
        {
            this.Context.SaveChanges(options);
        }

        /// <summary>
        /// Releases all resources     
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Releases all resources   
        /// </summary>
        /// <param name="disposing">A boolean value indicating whether or not to dispose managed resources</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!disposing) return;

            if (this.Context != null)
            {
                this.Context.Dispose();
                this.Context = null;
            }
        }
    }


IUserRepository.cs
public interface IUserRepository:IDisposable
    {
        bool CreateUser(string userId, string userName, string emailId);
        bool UpdateUser(string userId, string userName, string emailID);       
    }


UserRepository.cs
public class UserRepository : IUserRepository
    {
        #region "-- Variables/Objects --"

        private IRepository<DbModel.Models.User> EntityRepository;

        #endregion

        #region "-- New/Dispose --"

        public UserRepository()
        {
            this.EntityRepository = new DataRepository<DbModel.Models.User>(new DBEntities());
        }

        public void Dispose()
        {
            this.EntityRepository.Dispose();
        }

        #endregion
       
        #region -- Methods --

        public bool CreateUser(string userId, string userName, string emailId)
        {
            bool RetVal = false;
            DbModel.Models.User UserModel = new DbModel.Models.User();

            try
            {
                //-- Set parameter values in model
                UserModel.UserId = userId;
                UserModel.UserName = userName;
                UserModel.EmailId = emailId;               
                this.EntityRepository.Add(UserModel);
                this.EntityRepository.SaveChanges();
            }
            catch (Exception)
            {

                throw;
            }

            return RetVal;
        }


        public bool UpdateUser(string userId, string userName, string emailID)
        {
            bool RetVal = false;
            DbModel.Models.User UserModel = null;

            try
            {
                //-- get user object from EF Object context
                UserModel = (DbModel.Models.User)this.EntityRepository.First(u => u. UserID == userId);

                //-- update value               
                UserModel.UserName = userName;
                UserModel.EmailId = emailID;

                this.EntityRepository.SaveChanges();

                RetVal = true;
            }
            catch (Exception)
            {
                throw;
            }

            return RetVal;
        }
       
        #endregion
    }


UserController.cs
public class AccountController : Controller,IDisposable
{

private IUserRepository UserRepository = null;

public AccountController()
            : this(new UserRepository)
        {
            // do nothing
        }

        public AccountController(IUserRepository userRepository)
        {
            this._UserRepository = userRepository;
        }

        void IDisposable.Dispose()
        {
            base.Dispose();
            this._UserRepository.Dispose();
        }


[HttpPost]
        public ActionResult CreateUser()
        {
           
              -------------

              this._UserRepository.CreateUser(“ravi”, “ravi kumar gupta”, “ravig.spm@gmail.com);

                        
             -------------

       return View();
        }




No comments:

Post a Comment