Convert ICollectionView Filter into query expression RRS feed

  • Question

  • I have a read only WPF form that displays a list of "Dispatch" objects. An item can be edited in a separate maintenance screen. When the maintenance screen closes I rebuild the whole Context to get all the changes.

    Since the user will have applied filters and sorts to the list, I'd like to save the filter being used, and use it to reload the context. I don't know how to use the filter predicate in my query Where clause.

    something like:


    //Saving the filter whenever it changes
    ICollectionView _dispatchesView = CollectionViewSource.GetDefaultView(DispatchesListView.ItemsSource);
    var theFilter = _dispatchesView.Filter;
    //Re-query with the last filter used
    myContext.Dispatches.Where(...filter predicate here).Include(blah blah).Load();



    Bob - www.crowcoder.com
    • Edited by Molku Saturday, January 28, 2012 3:18 PM
    Saturday, January 28, 2012 1:53 PM


  • Hi Molku,

    The Filter property returns a Predicate<Object>, in order to use it within a Where() statement you'll need to convert it into a Func<T,Bool>. You can do this like so: 

    var theFilter = new Func<Dispatch,bool>(_dispatchesView.Filter);
    //Re-query with the last filter used
    myContext.Dispatches.Include(blah blah).Where(theFilter);

    Important Note: since you're using a compiled delegate to filter the results EF has no way of converting that into a T-SQL expression. This means that you'll be loading the entire contents of the Dispatches table into memory and then filtering it there.

    If what you want is to have the data filtered by the database before loading into memory then it'll be a bit more complicated. You'll have to decompile the delegate and convert it into an expression tree. Check this link if you want more info on that:




    • Marked as answer by Molku Saturday, January 28, 2012 8:25 PM
    Saturday, January 28, 2012 5:02 PM