2

I am testing the workings of WPF with Entity Framework. I have a SS table called Vendors {VendorCode, VendorName, Phone}.

I am sticking with only EF and I am able to display and navigate the recordset on a WPF form with buttons first, next, last etc. I used the instructions on the MSDN site (Create a simple data application with WPF and Entity Framework 6)

My problem is the recordset is sorted only in the order it was entered into SS. I would like to sort it by VendorCode or by VendorName to make it easier on the user. I can't seem to make it sort the recordset or table data coming through EF.

Can you please help? Thank you!

Here is a snippet of my code:

public Vendor newVendor { get; set; }
VendorsEntities context = new VendorsEntities();
CollectionViewSource VendorViewSource;
public MainWindow()
{
    InitializeComponent();
    newVendor = new Vendor();
    VendorViewSource = ((CollectionViewSource) 
                         (FindResource("VendorViewSource")));
    DataContext = this;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
    // this next line doesn't do it
    context.Vendors.OrderBy(Vendor => Vendor.VendorCode);
    context.Vendors.Load();
    VendorViewSource.Source = context.Vendors.Local;
}
private void NextCommandHandler(object sender, ExecutedRoutedEventArgs e)
{
    VendorViewSource.View.MoveCurrentToNext();
}

2 Answers 2

3

You would need to set the result of OrderBy method in to some variable and then use that as OrderBy will return a new reference, or you can use the set the reference of context.Vendors to the reference returned by OrderBy() method.

Try doing it like:

   var ordered = context.Vendors.OrderBy(Vendor => Vendor.VendorCode);
   VendorViewSource.Source = ordered;

another way can be to order it after bringing the result back, but it is not a recommended approach, first approach should be preferred, but just giving another option which is also possible:

var vendors = context.Vendors.Load().OrderBy(Vendor => Vendor.VendorCode);
VendorViewSource.Source = vendors;

Hope it helps!

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! This first solution also works great but I had to squeeze in the 'Local' as follows: var ordered = context.Vendors.Local.OrderBy(Vendor => Vendor.VendorCode);
0

You are sorting context, not displayed items. Try:

VendorViewSource.Source = context.Vendors.OrderBy(Vendor => Vendor.VendorCode);

1 Comment

Thank you so much. This works indeed, except I had to squeeze in the 'Local' as follows: VendorViewSource.Source = context.Vendors.Local.OrderBy(Vendor => Vendor.VendorCode);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.