Skip to main content

#AT Repository and Unit of Work Pattern - 5


UnitOfWork Layer creation

Add a folder in CMBusinessTyre project Named UnitOfWorkLayer
add 2 Interface and 2 class files.


IMyUnitOfWork
IGenericRepository
MyUnitOfWork
GenericRepository
public interface IMyUnitOfWork
   {
        int Commit();
   }
-------------------------------------------------
public interface IGenericRepository<T>
    {
        IEnumerable<T> GetData();
        T GetByID(object id);
         T Insert(T entity);
        void Delete(object id);
        void Update(T entityToUpdate);
        IEnumerable<T> FindBy(Expression<Func<T, bool>> predicate);
   
    }
-------------------------------------------------
public class MyUnitOfWork : IMyUnitOfWork, IDisposable
    {
        private GenericRepository<LoginUser> _loginUser;
        private GenericRepository<LogRegister> _logRegister;
        private GenericRepository<ContactInfo> _contactInfo;
        private GenericRepository<ContactAddress> _addressInfo;

        ContactManagerContext context = new ContactManagerContext();
   
        public GenericRepository<LoginUser> LoginUser
        {
            get
            {
                if (this._loginUser == null)
                    this._loginUser = new GenericRepository<LoginUser>(context);
                return _loginUser;
            }
        }
        public GenericRepository<LogRegister> LogRegister
        {
            get
            {
                if (this._logRegister == null)
                    this._logRegister = new GenericRepository<LogRegister>(context);
                return _logRegister;
            }
        }
        public GenericRepository<ContactInfo> ContactInfo
        {
            get
            {
                if (this._contactInfo == null)
                    this._contactInfo = new GenericRepository<ContactInfo>(context);
                return _contactInfo;
            }
        }
        public GenericRepository<ContactAddress> ContactAddress
        {
            get
            {
                if (this._addressInfo == null)
                    this._addressInfo = new GenericRepository<ContactAddress>(context);
                return _addressInfo;
            }
        }
        public int Commit()
        {
            try
            {
                return context.SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {
                // Retrieve the error messages as a list of strings.
                var errorMessages = ex.EntityValidationErrors
                        .SelectMany(x => x.ValidationErrors)
                        .Select(x => x.ErrorMessage);

                // Join the list to a single string.
                var fullErrorMessage = string.Join("; ", errorMessages);

                // Combine the original exception message with the new one.
                var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);

                // Throw a new DbEntityValidationException with the improved exception message.
                throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
            }
        }

        private bool disposed = false;
        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    context.Dispose();
                }
            }
            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
------------------------------------------------------------------
 public class GenericRepository<T> : IGenericRepository<T> where T : class
    {
        internal ContactManagerContext context;
        internal DbSet<T> dbSet;
        public GenericRepository(ContactManagerContext context)
        {
            this.context = context;
            this.dbSet = context.Set<T>();
        }
        public IEnumerable<T> GetData()
        {
            return dbSet.ToList();
        }
        public T GetByID(object id)
        {
            return dbSet.Find(id);
        }
        public IEnumerable<T> FindBy(Expression<Func<T, bool>> predicate)
        {
            IEnumerable<T> query = dbSet.Where(predicate).AsEnumerable();
            return query;
        }
        public T Insert(T entity)
        {
           return dbSet.Add(entity);
        }
        public void Delete(object id)
        {
            T entityToDelete = dbSet.Find(id);
            Delete(entityToDelete);
        }
        //public virtual T Delete(T entityToDelete)
        //{
        //    if (context.Entry(entityToDelete).State == EntityState.Detached)
        //    {
        //        dbSet.Attach(entityToDelete);
        //    }
        //    dbSet.Remove(entityToDelete);
        //}

        public void Update(T entityToUpdate)
        {
            dbSet.Attach(entityToUpdate);
            context.Entry(entityToUpdate).State = EntityState.Modified;
        }
    }
------------------------------------------------------------

Comments

Popular posts from this blog

#EF : DbEntityValidationException - How can I easily tell what caused the error?

While calling  SaveChanges  on my  DbContext , I get the following exception: System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details. This is all fine and dandy, but I don't want to attach a debugger every time this exception occurs. More over, in production environments I cannot easily attach a debugger so I have to go to great lengths to reproduce these errors. How can I see the details hidden within the  DbEntityValidationException ? Answer :  The easiest solution is to override SaveChanges on your entities class. You can catch the DbEntityValidationException, unwrap the actual errors and create a new DbEntityValidationException with the improved message. Create a partial class next to your SomethingSomething.Context.cs file. Use the code at the bottom of this post. That's it. Your implementation will automatically use the overriden Save...

#MVC : Why does Html.Label() not work with periods? or Why is @Html.Label() removing some characters

You are misusing the  Html.Label  method. It is for: Returns an HTML label element and the  property name of the property  that is represented by the specified expression. That's why it gets confused if you have a point  .  in the first parameter because it expects a property expression there. However, you can use the second overload: @Html . Label ( "" , String . Format ( "{0}. someText" , 1 )) Or just write out the HTML: <label> @String . Format ( "{0}. someText" , 1 )</ label > or <label class="WelcomeText" style="float: left">Welcome @Html.Label("", Model.USERID + " ( " + Model.ROLE + " )", new { @class = "WelcomeText" })</label> 

#SQL CTE(Common Table expressions)

SQL Server 2005 and on wards, a very powerful feather has been added for the programmers' benefit called CTE. CTE is again a temporary result set derived from the underling definition.  Common Table Expressions offer the same functionality as a view, but are ideal for one-off usages where you don't necessarily need a view defined for the system. CTE offers the advantages of improved readability and ease in maintenance of complex queries . The query can be divided into separate, simple, logical building blocks. These simple blocks can then be used to build more complex, interim CTEs until the final result set is generated. Common Table Expression Syntax A Common Table Expression contains three core parts: The CTE name (this is what follows the WITH keyword) The column list (optional) The query (appears within parentheses after the AS keyword) The query using the CTE must be the first query appearing after the CTE. Syntax : WITH expression_name [ ( column_n...