Showing posts with label Linq. Show all posts
Showing posts with label Linq. Show all posts

Friday, 1 May 2015

Revised : Generic data access for repository pattern


public class GenericDAL<T> : IDisposable
        where T : class
    {
        private EDMX.RMSModel model;
        private DbSet<T> dbSet;
        public GenericDAL()
        {
            model = new RMSModel();
            dbSet = model.Set<T>();
        }

        // Pass order by fields. form multiple fields pass fields by Comma(;) separated
         public IEnumerable<T> GetList(Expression<Func<T, bool>> where = null,
                                                        string orderBy = null,
                                                        SortDirection sortDir = SortDirection.Ascending)
        {
            IQueryable<T> query = dbSet;
            if (where != null)
            {
                query = query.Where(where);
            }

            if (!string.IsNullOrWhiteSpace(orderBy))
            {
                var orderFields = orderBy.Split(';');
                return OrderByDynamic(query, orderFields, sortDir);
            }
            else
            {
                return query.ToList();
            }
        }

        public T GetDetails(Expression<Func<T, bool>> where)
        {
            if (where != null)
            {
                IQueryable<T> query = dbSet;
                return query.Where(where).FirstOrDefault();
            }

            return null;
        }

        public int Insert(T entity)
        {
            dbSet.Add(entity);
            return model.SaveChanges();
        }

        public int Update(T entity)
        {
            dbSet.Attach(entity);
            model.Entry(entity).State = EntityState.Modified;
            return model.SaveChanges();
        }

        public int Delete(Expression<Func<T, bool>> where)
        {
            IQueryable<T> query = dbSet;
            T entity = query.Where(where).FirstOrDefault();
            dbSet.Remove(entity);
            return model.SaveChanges();
        }

        private List<T> OrderByDynamic(IQueryable<T> query = null, string[] sortExpressions = null,
                                                         SortDirection direction = SortDirection.Ascending)
        {
            // No sorting needed
            if ((sortExpressions == null) || (sortExpressions.Length <= 0))
            {
                return query.ToList();
            }

            // Let us sort it
            IOrderedEnumerable<T> orderedQuery = null;
            for (int i = 0; i < sortExpressions.Length; i++)
            {
                var index = i;
                Func<T, object> expression = item => item.GetType()
                                .GetProperty(sortExpressions[index])
                                .GetValue(item, null);

                if (direction == SortDirection.Ascending)
                {
                    orderedQuery = (index == 0) ?
                                              query.OrderBy(expression):
                                              orderedQuery.ThenBy(expression);
                }
                else
                {
                    orderedQuery = (index == 0) ?
                                              query.OrderByDescending(expression):
                                              orderedQuery.ThenByDescending(expression);
                }
            }

            return orderedQuery.ToList();
        }

        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                model.Dispose();
            }

            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

    }

Wednesday, 11 February 2015

Dynamic sorting in Linq


Code Snippet for Dynamic orderBy in Linq

public static IQueryable<T> OrderByDynamic<T>(this IQueryable<T> query, string attribute, SortDirection direction)
        {
            try
            {
                string orderMethodName = direction == SortDirection.Ascending ? "OrderBy" : "OrderByDescending";
                Type t = typeof(T);

                var param = Expression.Parameter(t);
                var property = t.GetProperty(attribute);

                return query.Provider.CreateQuery<T>(
                    Expression.Call(
                        typeof(Queryable),
                        orderMethodName,
                        new Type[] { t, property.PropertyType },
                        query.Expression,
                        Expression.Quote(
                            Expression.Lambda(
                                Expression.Property(param, property),
                                param))
                    ));
            }
            catch (Exception)
            {
                return query; // Return unsorted query
            }
        }


How to use :

  string sort = "Status"
   var status = DBContext.Status.Where(s => s.IsDeleted == false);
   SortDirection enumSort = sortDir.ToUpper() == "ASC" ? SortDirection.Ascending : SortDirection.Descending;
   status = status.OrderByDynamic(sort, enumSort).ToList();


Monday, 14 April 2014

Generic Repository with Object Context in Linq

Generic Repository with Object Context


Generic Class :

public class GenericRepository<T> : IDisposable where T : class
    {
        private XSharingEntities _ObjContext;
        IObjectSet<T> objSet;
        public GenericRepository(XSharingEntities context)
        {
            _ObjContext = context;
            objSet = _ObjContext.CreateObjectSet<T>();
        }

        public void Insert(T entity)
        {           
            if (entity != null)
            {
                objSet.Attach(entity);
                objSet.AddObject(entity);
            }
        }
        public void Delete(T entity)
        {
            if (entity != null)
            {
                objSet.DeleteObject(entity);
            }
        }
        public T getDetail(Expression<Func<T, bool>> where)
        {
            return objSet.Where(where).FirstOrDefault();
        }
        public IEnumerable<T> GetList()
        {
            return objSet.ToList();
        }
        public IEnumerable<T> GetList(Expression<Func<T,bool>> where)
        {

            return objSet.Where(where).ToList();
        }
        public void Save()
        {           
            _ObjContext.SaveChanges();
        }

        public void Dispose()
        {
            _ObjContext.Dispose();
            GC.SuppressFinalize(this);
        }
    }



Use generic class in our code


XSharingEntities objContext = new XSharingEntities();
public GenericRepository<SharingComment> objCFSCode
{
    get
    {

       GenericRepository<SharingComment> obj =
      new GenericRepository<SharingComment>(objContext);
      return obj;
    }
}

Do openrations in User Code
using (objCFSCode)
            {

                /// For Update
                var cmnt = objCFSCode.getDetail(p => p.CommentPK == 60217);               
                cmnt.Comment = "for Now";
                cmnt.CommentDate = DateTime.Now;
                cmnt.NotificationFK = 14;
                cmnt.UserFK = 1;
                objCFSCode.Save();

                // For Insert  
                SharingCFSCode obj = new SharingCFSCode();
                // SharingCFSCode is table
                obj.Application = "Test";
                obj.CFSCode = "AAAAAA";
                obj.CFSDescription = "This is Test CFS";
                obj.CFSPK = 123458;
                objCFSCode.Insert(cmnt);
                objCFSCode.Save();

                // for Delete
                objCFSCode.Delete(cmnt);
                objCFSCode.Save();
            }