Monday, 25 April 2016

MVC Repository Pattern With EntityFramwork- Getting Started

No comments

first we will create 3 projects in one solution for starting up our project

1. Test.Web - which contains our mvc project (MVC Project)
2. Repository.Pattern - which contains repository pattern
3. Test.Entities - which contains classes of database table


prerequisite - add entity framework from

1.Test.Web
------------------

create MVC project and create controller and view

HomeController.cs  -

 public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
  }


2. Repository.Pattern - 
------------------------------

add DataBaseContext.cs , unitofwork.cs for DbContext

DataBaseContext.cs -

  public class DataBaseContext : DbContext
    {
        private DbSet<Customer> Registration { get; set; }  

        public DataBaseContext()
            : base("Name=ConnectionString")
        {
            Configuration.LazyLoadingEnabled = false;
            Configuration.ProxyCreationEnabled = false;
        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
        }
    }

Unitofwork.cs - 

public class UnitOfWork : IDisposable
    {
        #region Declaration
        private DataBaseContext entities = null;
        private DbContextTransaction _transaction;
        #endregion

        #region Ctor
        public UnitOfWork()
        {
            //entities = new DBContext(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
            entities = new DataBaseContext();

        }
        #endregion

        #region Create Repository Instance
        public T Repository<T>() where T : class
        {
            Object[] args = { entities, this };

            var repository = Activator.CreateInstance(typeof(T), args);
            return (T)repository;
        }

        private Dictionary<Type, object> repositories = new Dictionary<Type, object>();
        public IRepository<T> RepositoryInstance<T>() where T : class
        {
            if (repositories.Keys.Contains(typeof(T)) == true)
            {
                return repositories[typeof(T)] as IRepository<T>;
            }
            IRepository<T> repo = new Repository<T>(entities, this);
            repositories.Add(typeof(T), repo);
            return repo;
        }

        #endregion

        #region DB Transactions
        public void BeginTransaction()
        {
            _transaction = entities.Database.BeginTransaction();
        }
        public bool Commit()
        {
            _transaction.Commit();
            return true;
        }
        public void Rollback()
        {
            _transaction.Rollback();
        }
        public void SaveChanges()
        {
            entities.SaveChanges();
        }
        #endregion

        #region Dispose
        private bool disposed = false;
        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    entities.Dispose();
                }
            }
            this.disposed = true;
        }
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        #endregion
    }

IRepository.cs -

 public interface IRepository<T> where T : class
    {
        IEnumerable<T> GetAll(Func<T, bool> predicate = null);
        T Get(Func<T, bool> predicate);
        void Add(T entity);
        void AddRange(List<T> entity);
        void Attach(T entity);
        void Update(T entity);
        void Delete(T entity);
        void DeleteRange(List<T> entity);
        IEnumerable<T> ExecWithStoreProcedure(string query, params object[] parameters);
        //T FindSingleBy<T>(Expression<Func<T, bool>> predicate);
        //IQueryable<T> FindAllBy<T>(Expression<Func<T, bool>> predicate);
        //IQueryable<T> FindBy<T, TKey>(Expression<Func<T, bool>> predicate, Expression<Func<T, TKey>> orderBy);

    }


Repository.cs - 


  public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
    {
        private DataBaseContext _context = null;
        private readonly DbSet<TEntity> _dbSet;
        UnitOfWork uom = null;
        public Repository(DataBaseContext context, UnitOfWork _uom)
        {
            _context = context;
            uom = _uom;
            var dbContext = context as DbContext;

            if (dbContext != null)
            {
                _dbSet = dbContext.Set<TEntity>();
            }
        }
        public IEnumerable<TEntity> GetAll(Func<TEntity, bool> predicate = null)
        {
            if (predicate != null)
            {
                return _dbSet.Where(predicate);
            }

            return _dbSet.AsEnumerable();
        }
        public TEntity FindSingleBy<TEntity>(Expression<Func<TEntity, bool>> predicate) where TEntity : class
        {
            if (predicate != null)
            {
                using (_context = new DataBaseContext())
                {
                    return _context.Set<TEntity>().Where(predicate).SingleOrDefault();
                }
            }
            else
            {
                throw new ArgumentNullException("Predicate value must be passed to FindSingleBy<T>.");
            }
        }

        public virtual IQueryable<TEntity> FindAllBy<TEntity>(Expression<Func<TEntity, bool>> predicate, DataBaseContext _context) where TEntity : class
        {
            if (predicate != null)
            {
                return _context.Set<TEntity>().Where(predicate);
            }
            else
            {
                throw new ArgumentNullException("Predicate value must be passed to FindAllBy<T>.");
            }
        }

        public IQueryable<TEntity> FindBy<TEntity, TKey>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, TKey>> orderBy) where TEntity : class
        {
            if (predicate != null)
            {
                if (orderBy != null)
                {
                    using (_context = new DataBaseContext())
                    {
                        return FindAllBy<TEntity>(predicate, _context).OrderBy(orderBy).AsQueryable<TEntity>(); ;
                    }
                }
                else
                {
                    throw new ArgumentNullException("OrderBy value must be passed to FindBy<T,TKey>.");
                }
            }
            else
            {
                throw new ArgumentNullException("Predicate value must be passed to FindBy<T,TKey>.");
            }
        }

        public TEntity Get(Func<TEntity, bool> predicate)
        {
            return _dbSet.FirstOrDefault(predicate);
        }

        public void Add(TEntity entity)
        {
            _dbSet.Add(entity);
            uom.SaveChanges();
        }

        public void AddRange(List<TEntity> entity)
        {
            _dbSet.AddRange(entity);
            uom.SaveChanges();
        }

        public void Update(TEntity entityToUpdate)
        {
            var entry = _context.Entry(entityToUpdate);
            var key = this.GetPrimaryKey(entry);

            if (entry.State == EntityState.Detached)
            {
                var currentEntry = _dbSet.Find(key);
                if (currentEntry != null)
                {
                    var attachedEntry = _context.Entry(currentEntry);
                    attachedEntry.CurrentValues.SetValues(entityToUpdate);
                }
                else
                {
                    _dbSet.Attach(entityToUpdate);
                    entry.State = EntityState.Modified;
                }
            }
        }

        private int GetPrimaryKey(DbEntityEntry entry)
        {
            var myObject = entry.Entity;
            var property =
                myObject.GetType()
                    .GetProperties()
                    .FirstOrDefault(prop => Attribute.IsDefined(prop, typeof(KeyAttribute)));
            return (int)property.GetValue(myObject, null);
        }

        public void Attach(TEntity entity)
        {
            _dbSet.Attach(entity);
            _context.Entry(entity).State = EntityState.Modified;
            uom.SaveChanges();
        }

        public void Delete(TEntity entity)
        {
            _context.Entry(entity).State = EntityState.Deleted;
            _dbSet.Remove(entity);
            uom.SaveChanges();
        }
        public void DeleteRange(List<TEntity> entity)
        {
            _dbSet.RemoveRange(entity);
            uom.SaveChanges();
        }
        public IEnumerable<TEntity> ExecWithStoreProcedure(string query, params object[] parameters)
        {
            return _context.Database.SqlQuery<TEntity>(query, parameters);
        }

    }


Create Customer repository noe

ContactsRepository.cs


 public class ContactsRepository: Repository<Contacts>
    {
        private DataBaseContext _context = null;
        public ContactsRepository(DataBaseContext context, UnitOfWork _uom)
            : base(context, _uom)
        {
            _context = context;
        }
        public void AddContacts(Contacts Contacts)
        {
            var dbset = _context.Set<Contacts>();
            dbset.Add(Contacts);
            _context.SaveChanges();
        }
     

        public Contacts GetContactsById(int contactId)
        {
            var dbset = _context.Set<Contacts>();
            var contacts = dbset.FirstOrDefault(x => x.ContactsId == contactId);
            if (contacts != null)
            {
                return contacts;
            }
            return null;

        }


    }


3.Test.Entities
--------------------


   public class Contacts
    {
        [Key]
        public int ContactsId { get; set; }
        public int CustomerId { get; set; }
        [Required]
        [StringLength(35)]
        public string Address1 { get; set; }
        [StringLength(35)]
        public string Address2 { get; set; }
        [Required]

        public int CountryId { get; set; }
        //[Required]

        public string StateId { get; set; }
        [Required]
        [StringLength(50)]
        public string City { get; set; }
        [Required]
        [StringLength(10)]
        public string ZIP { get; set; }
        [Required]
        [StringLength(15)]
}

using repository in controller--

HomeController.cs  -

 public class HomeController : Controller
    {
        public ActionResult Index()
        {
                 var insertContacts = uom.Repository<ContactsRepository>();
                Contacts contacts = new Contacts();
                contacts.CustomerId = SessionFactory.Instance.CurrentCustomer.CustomerId;
                contacts.Address1 = shipmentModel.ShipFrom.Address1;
                contacts.Address2 = shipmentModel.ShipFrom.Address2;
                contacts.CountryId = shipmentModel.ShipFrom.CountryId;
                contacts.StateId = shipmentModel.ShipFrom.StateId;
                contacts.City = shipmentModel.ShipFrom.City;
                contacts.ZIP = shipmentModel.ShipFrom.ZIP;
                contacts.Phone = shipmentModel.ShipFrom.Phone;              
                insertContacts.AddContacts(contacts);              
                return View();
        }
  }