dimanche 10 mai 2015

Entity Framework find next / previous with different orders / indexes

I have a WPF MVVM application with a view that displays a current unique entity. There are previous and next buttons to move to other entities. The finding of entities is directly queried back on the database, and are not held in any collection - the database contains millions of records.

On my view, I want to be able to find next and previous entities based on the control / text box that is currently selected e.g. if I select a title text box then click next, it would find the next record in title sequence, and if I did it on a release date field it would find the next record in release date sequence. This mechanism of knowing what field is selected works, getting the information back to the view model, I'm just wondering the best method of controlling this in Entity Framework via LINQ.

I've included a basic excerpt of next and previous methods, with code that works (ISBN is a string PK, and title is a string). It is possible that there could be many other find orders, in different views with indexes containing many properties, so I'm just wondering if there is a more efficient, elegant way to do this... can anyone suggest a better alternative?

Many thanks

            // Find Next Method
            Product result = null;
            if (this.index == 1) result = db.Products.Where(x => x.ISBN.CompareTo(Product.ISBN) > 0).OrderBy(x => x.ISBN).FirstOrDefault();
            if (this.index == 2) result = db.Products.Where(x => (x.Title == Product.Title && (x.ISBN.CompareTo(Product.ISBN) > 0)) || x.Title.CompareTo(Product.Title) > 0).OrderBy(x => x.Title).FirstOrDefault();


            // Find Previous Method
            Product result = null;
            if (this.index == 1) result = db.Products.Where(x => x.ISBN.CompareTo(Product.ISBN) < 0).OrderByDescending(x => x.ISBN).FirstOrDefault();
            if (this.index == 2) result = db.Products.Where(x => (x.Title == Product.Title && (x.ISBN.CompareTo(Product.ISBN) < 0)) || x.Title.CompareTo(Product.Title) < 0).OrderByDescending(x => x.Title).FirstOrDefault();

Aucun commentaire:

Enregistrer un commentaire