locked
Entity Framework: How to enable paging support for repository pattern RRS feed

  • Question

  • User1183902823 posted

    i found a code which seems work. just tell me how use the below code to return paged customer...may be 20 customer. also tell me how to enable sorting.

    give me a small sample code which fetch customer with paging and sorting. thanks

    public interface IPaged<T> : IEnumerable<T>
        {
            ///<summary>
            /// Get the total entity count.
            ///</summary>
            int Count { get; }
    
            ///<summary>
            /// Get a range of persited entities.
            ///</summary>
            IEnumerable<T> GetRange(int index, int count);
        }
    
    
    public class Paged<T> : IPaged<T>
        {
            private readonly IQueryable<T> source;
    
            public Paged(IQueryable<T> source)
            {
                this.source = source;
            }
    
            public IEnumerator<T> GetEnumerator()
            {
                return source.GetEnumerator();
            }
    
            IEnumerator IEnumerable.GetEnumerator()
            {
                return GetEnumerator();
            }
    
            public int Count
            {
                get { return source.Count(); }
            }
    
            public IEnumerable<T> GetRange(int index, int count)
            {
                return source.Skip(index).Take(count);
            }
        }
    
    
    public IPaged<Customer> GetCustomers();
    Wednesday, December 13, 2017 1:16 PM

Answers

  • User-832373396 posted

    <g class="gr_ gr_60 gr-alert gr_gramm gr_inline_cards gr_run_anim Punctuation only-ins replaceWithoutSep" id="60" data-gr-id="60">Hi</g> tridip,

    Sir, after debugging it, here is the full design:

     public interface IPaged<T> : IEnumerable<T>
        {
            ///<summary>
            /// Get the total entity count.
            ///</summary>
            int Count { get; }
    
            ///<summary>
            /// Get a range of persited entities.
            ///</summary>
            IEnumerable<T> GetRange(int index, int count, Expression<Func<T, int>> orderLambda);
        }
    
    
        public class Paged<T> : IPaged<T>
        {
            private readonly IQueryable<T> source;
    
            public Paged(IQueryable<T> source)
            {
                this.source = source;
            }
    
            public IEnumerator<T> GetEnumerator()
            {
                return source.GetEnumerator();
            }
    
            IEnumerator IEnumerable.GetEnumerator()
            {
                return GetEnumerator();
            }
    
            public int Count
            {
                get { return source.Count(); }
            }
    
            public IEnumerable<T> GetRange(int index, int count, Expression<Func<T, int>> orderLambda)
            {
                return source.OrderBy(orderLambda).Skip(index).Take(count);
            }
    
            ////--------------------------------
            public T GetFirst(Expression<Func<T, bool>> whereLambda)
            {
    
                return source.Where(whereLambda).FirstOrDefault();
            }
            public IEnumerable<T> GetAll()
            {
                return source.ToList();
            }
            public IEnumerable<T> OrderBy(Expression<Func<T,  int>> orderLambda)
            {
                return source.OrderBy(orderLambda);
            }
    
        }

    and  the working example to use it:

       public class Student1Controller : Controller
        {
            private NorthwindContext NorthwindDB = new NorthwindContext();
            public Student1Controller() {
     
            }
            public ActionResult Index5() {
                Debug.WriteLine("1ab");
                //List<APerson> Persons = new List<APerson> {
                //        new APerson { APersonName="Person A" },
                //        new APerson { APersonName="Person B" },
                //        new APerson { APersonName="Person C" },
                //        new APerson { APersonName="Person D" },
                //    };
    
                //NorthwindDB.APersons.AddRange(Persons);
                //NorthwindDB.SaveChanges();// add person
     
    
                Paged<APerson> ob = new Paged<APerson>(NorthwindDB.APersons.AsQueryable());//pass list collection
                APerson ap = ob.GetFirst(c => c.APersonID>1);  // pass lamda and get result
    
                Debug.WriteLine(ap == null?"aaa" : ap.APersonName);
                List<APerson> cList = ob.OrderBy(e => e.APersonID).ToList();  // pass lamda and get result
                IEnumerable<APerson> cList2 = ob.GetRange(1, 2, d => d.APersonID) ;

    (note: you could see that you need to pass  NorthwindDB.APersons )  

    by the way, here is the better way that it only needs to pass NorthwindDB context;

    Full code:

    In EFDal.cs:

      public interface IEFDal<T>
        {
            T GetFirst(Expression<Func<T, bool>> whereLambda);
    
        }
        public class EFDal<T> : IEFDal<T> where T : class
        {
            protected DbContext DbContext { get; set; }
            protected DbSet<T> DbSet { get; set; }
            public EFDal(DbContext context)
            {
                if (context == null)
                    throw new ArgumentNullException("dbContext");
                DbContext = context;
                DbSet = DbContext.Set<T>();
            }
     public T GetFirst(Expression<Func<T, bool>> whereLambda)
            {
    
                return DbSet.Where(whereLambda).FirstOrDefault();
            }
            public IEnumerable<T> GetAll()
            {
                return DbSet.ToList();
            }
            public IEnumerable<T> OrderBy(Expression<Func<T, object>> orderLambda)
            {
                return DbSet.OrderBy(orderLambda);
            }
    
            
        }
    

    And in CallSomething.cs:

    public class CallSomething
        {
            public DbContext DbContext { get; set; }
    
             public void Method06()
            {
                EFDal<TodoItem> ob = new EFDal<TodoItem>(DbContext);//pass a context
                TodoItem a = ob.GetFirst(c => c.Id == 2);  // pass lamda and get result
                List<TodoItem> a = ob.OrderBy(c => c.Id );  // pass lamda and get result
                //debug it, here ,and it could get first element successfully;
            }
        }
    

    and in MyFacade.cs :

      public class MyFacade
        {
            public static CallSomething tocall = new CallSomething();
            public static DbContext _context { get; set; }
            public static void Facade()
            {
                tocall.DbContext = _context;
                tocall.Method06();
            }       
        }
    

    And at controller:

      #region customize
            public IActionResult IndexFacade()
            {
    private NorthwindContext NorthwindDB = new NorthwindContext(); MyFacade._context = NorthwindDB ;
    MyFacade.Facade(); return View(); }

    and, as personal,  I think that to compare Façade design pattern is better :)

    With regards, Angelina Jolie

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, December 14, 2017 9:21 AM
  • User-832373396 posted

    <g class="gr_ gr_9 gr-alert gr_gramm gr_inline_cards gr_run_anim Punctuation only-ins replaceWithoutSep" id="9" data-gr-id="9">Hi</g> <g class="gr_ gr_7 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="7" data-gr-id="7">tridip</g>,

    tridip1974

    can we create a paging extension which we can use with my repository?

    Sir, after the test, please refer to the working code as shown below;

      private BookContext _BookContext = new BookContext ();
    public ActionResult Index() { BookRepository oB = new BookRepository(_BookContext );
    List<Book> mybookArry= oB.GetRange(1, 20,a=>a.Id, c => c.Title != "Title2"&& c.Id>3).ToList();

    Full code:

     public class Book
        {
            [Key]
            public int Id { get; set; }
            [Required]
            [MaxLength(30)]
            public string Title { get; set; }
            public string Authers { get; set; }
    
            [Column("Year")]
            [Display(Name = "Publish Year")]
            public string publishYear { get; set; }
    
            [Column("Price")]
            [Display(Name = "Price")]
            public decimal BasePrice { get; set; }
        }
    public class BookRepository : IBookRepository
        {
            private BookContext _context;
    
            public BookRepository(BookContext bookContext)
            {
                this._context = bookContext;
            }
    
            public IEnumerable<Book> GetBooks()
            {
                return _context.Books.ToList();
            }
      
            public Book GetBookByID(int id)
            {
                return _context.Books.Find(id);
            }
            public IEnumerable<Book> GetRange(int index, int count, Expression<Func<Book, int>> orderLambda)
            {
                return _context.Books.OrderBy(orderLambda).Skip((index-1)*count).Take(count).ToList();
            }
            public IEnumerable<Book> GetRange(int index, int count, Expression<Func<Book, int>> orderLambda, Expression<Func<Book, bool>> whereLambda)
            {
                return _context.Books.Where(whereLambda).OrderBy(orderLambda).Skip((index-1)*count).Take(count).ToList();
            }
    
            public void InsertBook(Book book)
            {
                _context.Books.Add(book);
            }
    
            public void DeleteBook(int bookID)
            {
                Book book = _context.Books.Find(bookID);
                _context.Books.Remove(book);
            }
    
            public void UpdateBook(Book book)
            {
                _context.Entry(book).State = EntityState.Modified;
            }
    
            public void Save()
            {
                _context.SaveChanges();
            }
    
            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);
            }
        }

    and

      public interface IBookRepository : IDisposable
        {
            IEnumerable<Book> GetBooks();
            Book GetBookByID(int bookId);
            void InsertBook(Book book);
            void DeleteBook(int bookID);
            void UpdateBook(Book book);
            void Save();
        }

    With regards, Angelina Jolie

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, December 19, 2017 6:56 AM

All replies

  • User-832373396 posted

    <g class="gr_ gr_60 gr-alert gr_gramm gr_inline_cards gr_run_anim Punctuation only-ins replaceWithoutSep" id="60" data-gr-id="60">Hi</g> tridip,

    Sir, after debugging it, here is the full design:

     public interface IPaged<T> : IEnumerable<T>
        {
            ///<summary>
            /// Get the total entity count.
            ///</summary>
            int Count { get; }
    
            ///<summary>
            /// Get a range of persited entities.
            ///</summary>
            IEnumerable<T> GetRange(int index, int count, Expression<Func<T, int>> orderLambda);
        }
    
    
        public class Paged<T> : IPaged<T>
        {
            private readonly IQueryable<T> source;
    
            public Paged(IQueryable<T> source)
            {
                this.source = source;
            }
    
            public IEnumerator<T> GetEnumerator()
            {
                return source.GetEnumerator();
            }
    
            IEnumerator IEnumerable.GetEnumerator()
            {
                return GetEnumerator();
            }
    
            public int Count
            {
                get { return source.Count(); }
            }
    
            public IEnumerable<T> GetRange(int index, int count, Expression<Func<T, int>> orderLambda)
            {
                return source.OrderBy(orderLambda).Skip(index).Take(count);
            }
    
            ////--------------------------------
            public T GetFirst(Expression<Func<T, bool>> whereLambda)
            {
    
                return source.Where(whereLambda).FirstOrDefault();
            }
            public IEnumerable<T> GetAll()
            {
                return source.ToList();
            }
            public IEnumerable<T> OrderBy(Expression<Func<T,  int>> orderLambda)
            {
                return source.OrderBy(orderLambda);
            }
    
        }

    and  the working example to use it:

       public class Student1Controller : Controller
        {
            private NorthwindContext NorthwindDB = new NorthwindContext();
            public Student1Controller() {
     
            }
            public ActionResult Index5() {
                Debug.WriteLine("1ab");
                //List<APerson> Persons = new List<APerson> {
                //        new APerson { APersonName="Person A" },
                //        new APerson { APersonName="Person B" },
                //        new APerson { APersonName="Person C" },
                //        new APerson { APersonName="Person D" },
                //    };
    
                //NorthwindDB.APersons.AddRange(Persons);
                //NorthwindDB.SaveChanges();// add person
     
    
                Paged<APerson> ob = new Paged<APerson>(NorthwindDB.APersons.AsQueryable());//pass list collection
                APerson ap = ob.GetFirst(c => c.APersonID>1);  // pass lamda and get result
    
                Debug.WriteLine(ap == null?"aaa" : ap.APersonName);
                List<APerson> cList = ob.OrderBy(e => e.APersonID).ToList();  // pass lamda and get result
                IEnumerable<APerson> cList2 = ob.GetRange(1, 2, d => d.APersonID) ;

    (note: you could see that you need to pass  NorthwindDB.APersons )  

    by the way, here is the better way that it only needs to pass NorthwindDB context;

    Full code:

    In EFDal.cs:

      public interface IEFDal<T>
        {
            T GetFirst(Expression<Func<T, bool>> whereLambda);
    
        }
        public class EFDal<T> : IEFDal<T> where T : class
        {
            protected DbContext DbContext { get; set; }
            protected DbSet<T> DbSet { get; set; }
            public EFDal(DbContext context)
            {
                if (context == null)
                    throw new ArgumentNullException("dbContext");
                DbContext = context;
                DbSet = DbContext.Set<T>();
            }
     public T GetFirst(Expression<Func<T, bool>> whereLambda)
            {
    
                return DbSet.Where(whereLambda).FirstOrDefault();
            }
            public IEnumerable<T> GetAll()
            {
                return DbSet.ToList();
            }
            public IEnumerable<T> OrderBy(Expression<Func<T, object>> orderLambda)
            {
                return DbSet.OrderBy(orderLambda);
            }
    
            
        }
    

    And in CallSomething.cs:

    public class CallSomething
        {
            public DbContext DbContext { get; set; }
    
             public void Method06()
            {
                EFDal<TodoItem> ob = new EFDal<TodoItem>(DbContext);//pass a context
                TodoItem a = ob.GetFirst(c => c.Id == 2);  // pass lamda and get result
                List<TodoItem> a = ob.OrderBy(c => c.Id );  // pass lamda and get result
                //debug it, here ,and it could get first element successfully;
            }
        }
    

    and in MyFacade.cs :

      public class MyFacade
        {
            public static CallSomething tocall = new CallSomething();
            public static DbContext _context { get; set; }
            public static void Facade()
            {
                tocall.DbContext = _context;
                tocall.Method06();
            }       
        }
    

    And at controller:

      #region customize
            public IActionResult IndexFacade()
            {
    private NorthwindContext NorthwindDB = new NorthwindContext(); MyFacade._context = NorthwindDB ;
    MyFacade.Facade(); return View(); }

    and, as personal,  I think that to compare Façade design pattern is better :)

    With regards, Angelina Jolie

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, December 14, 2017 9:21 AM
  • User1183902823 posted

    @Angelina your code becomes very complicated to understand. can we create a paging extension which we can use with my repository?

    public interface IPaged<T> : IEnumerable<T>
        {
            ///<summary>
            /// Get the total entity count.
            ///</summary>
            int Count { get; }
    
            ///<summary>
            /// Get a range of persited entities.
            ///</summary>
            IEnumerable<T> GetRange(int index, int count, Expression<Func<T, int>> orderLambda);
        }
    
    
        public class Paged<T> : IPaged<T>
        {
            private readonly IQueryable<T> source;
    
            public Paged(IQueryable<T> source)
            {
                this.source = source;
            }
    
            public IEnumerator<T> GetEnumerator()
            {
                return source.GetEnumerator();
            }
    
            IEnumerator IEnumerable.GetEnumerator()
            {
                return GetEnumerator();
            }
    
            public int Count
            {
                get { return source.Count(); }
            }
    
            public IEnumerable<T> GetRange(int index, int count, Expression<Func<T, int>> orderLambda)
            {
                return source.OrderBy(orderLambda).Skip(index).Take(count);
            }
    
            ////--------------------------------
            public T GetFirst(Expression<Func<T, bool>> whereLambda)
            {
    
                return source.Where(whereLambda).FirstOrDefault();
            }
            public IEnumerable<T> GetAll()
            {
                return source.ToList();
            }
            public IEnumerable<T> OrderBy(Expression<Func<T,  int>> orderLambda)
            {
                return source.OrderBy(orderLambda);
            }
    
        }

    suppose below is my repository

    This is books model
        -----------------------
        public class Book
        {
            [Key]
            public int Id { get; set; }
            [Required]
            [MaxLength(30)]
            public string Title { get; set; }
            public string Authers { get; set; }
     
            [Column("Year")]
            [Display(Name = "Publish Year")]
            public string publishYear { get; set; }
     
            [Column("Price")]
            [Display(Name = "Price")]
            public decimal BasePrice { get; set; }
        }
       
        Repository interface
        --------------------
        public interface IBookRepository : IDisposable
            {
                IEnumerable<Book> GetBooks();
                Book GetBookByID(int bookId);
                void InsertBook(Book book);
                void DeleteBook(int bookID);
                void UpdateBook(Book book);
                void Save();
        }
    
    
    Book repository
    --------------------
    public class BookRepository : IBookRepository
        {
            private BookContext _context;
     
            public BookRepository(BookContext bookContext)
            {
                this._context = bookContext;
            }
     
            public IEnumerable<book> GetBooks()
            {
                return _context.Books.ToList();
            }
     
            public Book GetBookByID(int id)
            {
                return _context.Books.Find(id);
            }
     
            public void InsertBook(Book book)
            {
                _context.Books.Add(book);
            }
     
            public void DeleteBook(int bookID)
            {
                Book book = _context.Books.Find(bookID);
                _context.Books.Remove(book);
            }
     
            public void UpdateBook(Book book)
            {
                _context.Entry(book).State = EntityState.Modified;
            }
     
            public void Save()
            {
                _context.SaveChanges();
            }
     
            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);
            }
        }
    
    BookRepository oB=new BookRepository();
    ob.GetBooks().Where(e=> e.title='asp.net' && Authers ='joy').GetRange(1,20).ToList();

    can't we do like that?

    if possible then please show me how to refactor the existing code. thanks

    Friday, December 15, 2017 11:38 AM
  • User-832373396 posted

    <g class="gr_ gr_9 gr-alert gr_gramm gr_inline_cards gr_run_anim Punctuation only-ins replaceWithoutSep" id="9" data-gr-id="9">Hi</g> <g class="gr_ gr_7 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="7" data-gr-id="7">tridip</g>,

    tridip1974

    can we create a paging extension which we can use with my repository?

    Sir, after the test, please refer to the working code as shown below;

      private BookContext _BookContext = new BookContext ();
    public ActionResult Index() { BookRepository oB = new BookRepository(_BookContext );
    List<Book> mybookArry= oB.GetRange(1, 20,a=>a.Id, c => c.Title != "Title2"&& c.Id>3).ToList();

    Full code:

     public class Book
        {
            [Key]
            public int Id { get; set; }
            [Required]
            [MaxLength(30)]
            public string Title { get; set; }
            public string Authers { get; set; }
    
            [Column("Year")]
            [Display(Name = "Publish Year")]
            public string publishYear { get; set; }
    
            [Column("Price")]
            [Display(Name = "Price")]
            public decimal BasePrice { get; set; }
        }
    public class BookRepository : IBookRepository
        {
            private BookContext _context;
    
            public BookRepository(BookContext bookContext)
            {
                this._context = bookContext;
            }
    
            public IEnumerable<Book> GetBooks()
            {
                return _context.Books.ToList();
            }
      
            public Book GetBookByID(int id)
            {
                return _context.Books.Find(id);
            }
            public IEnumerable<Book> GetRange(int index, int count, Expression<Func<Book, int>> orderLambda)
            {
                return _context.Books.OrderBy(orderLambda).Skip((index-1)*count).Take(count).ToList();
            }
            public IEnumerable<Book> GetRange(int index, int count, Expression<Func<Book, int>> orderLambda, Expression<Func<Book, bool>> whereLambda)
            {
                return _context.Books.Where(whereLambda).OrderBy(orderLambda).Skip((index-1)*count).Take(count).ToList();
            }
    
            public void InsertBook(Book book)
            {
                _context.Books.Add(book);
            }
    
            public void DeleteBook(int bookID)
            {
                Book book = _context.Books.Find(bookID);
                _context.Books.Remove(book);
            }
    
            public void UpdateBook(Book book)
            {
                _context.Entry(book).State = EntityState.Modified;
            }
    
            public void Save()
            {
                _context.SaveChanges();
            }
    
            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);
            }
        }

    and

      public interface IBookRepository : IDisposable
        {
            IEnumerable<Book> GetBooks();
            Book GetBookByID(int bookId);
            void InsertBook(Book book);
            void DeleteBook(int bookID);
            void UpdateBook(Book book);
            void Save();
        }

    With regards, Angelina Jolie

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, December 19, 2017 6:56 AM
  • User-832373396 posted

    Hi tridip,

    Sir, what happens? why unmark?

    May I know whether there is some question about the new design of your code?

    Welcome to back if any question.

    Bests, Jolie

    Wednesday, December 20, 2017 8:00 AM