views:

147

answers:

1

I have a collection of ViewModel objects that I am attempting to sort.

This is an abbreviated view of my ViewModel class:

public class BookIndexFormViewModel
{
    //Properties
    public Book Book                        { get; set; }

    //Constructor
    public BookIndexFormViewModel(Book book)
    {
        Book = book;
    }

This is the method in my repository where I am instantiating my collection:

public IQueryable<BookIndexFormViewModel> GetAllBooks()
    {
        return db.Books.Select(b => new BookIndexFormViewModel(b));
    }

This is an abbreviated view of me attempting to order the collection, which causes an exception.

var books = _bookRepository.GetAllBooks();
books.OrderBy(x => x.Book.Name);

This is the exception that is thrown:

The member 'TheBibliophile.Controllers.BookIndexFormViewModel.Book' has no supported translation to SQL.

I'm stumped on this one. I'm not trying to invoke a method when I receive this exception, like the majority of cases I see on the net. I'm just trying to sort by a property of a property in my ViewModel. Any tips?

+1  A: 

This results in an error because what you are doing, new BookIndexFormViewModel(b), cannot be mapped to SQL. You want to orderby before you wrap the Book with BookIndexFormViewModel. Something like this should work inside GetAllBooks()

return db.Books.OrderBy(x => x.Name).ToList().Select(b => new BookIndexFormViewModel(b));

amrinder