我有一個視圖模型,結合了3個模型的數據。

  public class VendorVM
    {
        public IEnumerable<Vendor> Vendors { get; set; }
        public IEnumerable<Promo> Promos { get; set; }
        public IEnumerable<Contact> Contacts { get; set; }
        public IEnumerable<Distributor> Distributors { get; set; }
    }

這是控制器:

     public async Task<IActionResult> Index(int? id)
            {
ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
            ViewData["DateSortParm"] = sortOrder == "Date" ? "date_desc" : "Date";

           var viewModel = new VendorVM();
                    viewModel.Vendors = await _context.Vendors
                        .Include(i => i.Promos)
                        .Include(i => i.Contacts)
                        .Include(i => i.Distributors)
                        .AsNoTracking()
                        .ToListAsync();
                    if (id != null)
                    {
                        ViewData["VendorID"] = id.Value;
                        Vendor vendorVM = viewModel.Vendors.Where(
                            i => i.VendorID == id.Value).Single();
                        viewModel.Promos = vendorVM.Promos.ToList();
                        viewModel.Contacts = vendorVM.Contacts.ToList();
                        viewModel.Distributors = vendorVM.Distributors.ToList();

 switch(sortOrder)
                {
                    case "name_desc":
                        viewModel.Vendors = viewModel.Vendors.OrderByDescending(i => i.VendorName);
                        break;
                    case "Date":
                        viewModel.Vendors = viewModel.Vendors.OrderBy(i => i.Distributors.OrderBy(v => v.LastUpdateDate));
                        break;
                    case "date_desc":
                        viewModel.Vendors = viewModel.Vendors.OrderByDescending(i => i.Distributors.OrderByDescending(v => v.LastUpdateDate)));
                        break;
                    default:
                        viewModel.Vendors = viewModel.Vendors.OrderBy(i => i.VendorName);
                        break;
                    }
                    return View(viewModel);
    }

如何為此視圖模型添加排序功能?我想按VendorName和LastUpdateDate排序。我在這裡遵循這個教程: https//docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/sort-filter-page 。它不適用於我的視圖模型,因為我只能對供應商信息進行排序。我想對促銷,聯繫人和經銷商信息進行排序。

一般承認的答案

不確定你在這裡要做什麼:

viewModel.Vendors = viewModel.Vendors.OrderBy(i => i.Distributors.OrderBy(v => v.LastUpdateDate));

它的語義對我來說沒有意義,我確信編譯器同樣困惑。您是否嘗試對VendorsDistributors集合進行排序?那將是兩個單獨的排序操作。像這樣的東西:

viewModel.Vendors = viewModel.Vendors.OrderBy(i => i.LastUpdateDate));
viewModel.Distributors = viewModel.Distributors.OrderBy(v => v.LastUpdateDate));

當您對要在另一個集合上執行的一個集合上執行操作時,您只需對該另一個集合執行相同的操作。這些陳述不會以某種方式相互嵌套。


熱門答案

我會使用.Order By(...)在tolistasync調用之前的原始查詢



Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow