簡體   English   中英

使用實體框架在WPF中排序

[英]sorting in wpf using entity framework

我正在使用實體框架測試WPF的工作。 我有一個名為Vendors {VendorCode, VendorName, Phone}的SS表。

我只使用EF,並且能夠使用第一個,下一個,最后一個等按鈕在WPF表單上顯示和導航記錄集。我使用了MSDN網站上的說明(使用WPF和Entity Framework 6創建一個簡單的數據應用程序)

我的問題是記錄集僅按輸入SS的順序排序。 我想按VendorCode或VendorName對其進行排序,以使其對用戶更容易。 我似乎無法使它對通過EF來的記錄集或表數據進行排序。

你能幫忙嗎? 謝謝!

這是我的代碼片段:

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();
}

您需要將OrderBy方法的結果設置為某個變量,然后使用該變量,因為OrderBy將返回新的引用,或者您可以使用set context.Vendors的引用來設置由OrderBy()方法返回的引用。

嘗試這樣做:

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

另一種方法是將結果重新排序后進行排序,但這不是建議的方法,應該首選第一種方法,而只是給出另一種可能的選擇:

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

希望能幫助到你!

您正在排序上下文,而不是顯示的項目。 嘗試:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM