2014-04-26 3 views
0

그래서 나는 MVC의 완전한 초보자이며 이것에 대해 많은 어려움을 겪고 있습니다.동적 모델 정렬

나는 나의 DB 테이블이 항목 컨트롤러의 엔티티 프레임 워크에 IEntryRepository에 의해 인스턴스화되고있다. 데이터를 가져올 수 있으며 페이징 도우미가 작동하는 것 같습니다. 결과를 필터링 할 수도 있습니다. 그러나 열을 정렬하는 방법을 알아내는 데 끔찍한 시간을 보내고 있습니다. 보기에서

public ViewResult Entries(string Specialty, string sortOrder, string CurrentSort, int page = 1) 
    { 
     //ViewBag.CurrentSort = sortOrder; 

     //sortOrder = String.IsNullOrEmpty(sortOrder) ? "TimeStamp" : sortOrder; 

     //for testing 
     sortOrder = "Case"; 

     switch (sortOrder) 
     { 
      case "Case": 
       sortOrder = "p.Case"; 
       break; 

      case "Timestamp": 
       sortOrder = "p.TimeStamp"; 
       break; 

      case "Origin": 
       sortOrder = "Origin"; 
       break; 

      case "AssignedTo": 
       sortOrder = "AssignedTo"; 
       break; 

      case "AssignedBy": 
       sortOrder = "AssignedBy"; 
       break; 
     } 

     EntryListViewModel model = new EntryListViewModel 
     { 
      Entry = repository.Entries.AsQueryable() 
      .Where(p => Specialty == null || p.Sub == Specialty) 
      .OrderBy(p => sortOrder) 
      .Skip((page - 1) * pagesize) 
      .Take(pagesize), 
      PagingInfo = new PagingInfo 
      { 
       CurrentPage = page, 
       ItemsPerPage = pagesize, 
       TotalItems = Specialty == null ? 
       repository.Entries.Count() : 
       repository.Entries.Where(p => p.Sub == Specialty).Count() 
      }, 

      CurrentCategory = Specialty 
     }; 


     return View(model); 
    } 

:

컨트롤러에서

나는이 오류의 무리가 알고

@model ProjectSquid.WebUI.Models.EntryListViewModel 


<table class="entries"> 
    <thead> 
     <tr> 
      <th>@Html.ActionLink("Case Number", "Entries", "Entry", new {Specialty = Model.CurrentCategory, sortOrder = "Case", CurrentSort = ViewBag.CurrentSort}) </th> 
      <th>Time Stamp </th> 
      <th>Origin </th> 
      <th>Assigned To </th> 
      <th>Assigned By </th> 
      <th>Customer Name </th> 
      <th>Customer Phone </th> 
      <th>Comments </th> 
     </tr> 
    </thead> 
    <tbody class="entry"> 
     @foreach (var p in Model.Entry) 
     { 
      <tr> 
       <td title="@p.Case">@p.Case</td> 
       <td title="@p.TimeStamp">@p.TimeStamp</td> 
       <td title="@p.Origin">@p.Origin</td> 
       <td title="@p.AssignedTo">@p.AssignedTo</td> 
       <td title="@p.AssignedBy">@p.AssignedBy</td> 
       <td title="@p.CustomerName">@p.CustomerName</td> 
       <td title="@p.CustomerPhone">@p.CustomerPhone</td> 
       <td title="@p.Comments">@p.Comments</td> 
       @if (Context.User.Identity.IsAuthenticated){<td>Delete</td>} 
      </tr>} 
    </tbody> 
</table> 

<div class="pager"> 
     @Html.PageLinks(Model.PagingInfo, x => Url.Action("Entries", 
     new { page = x, category = Model.CurrentCategory })) 
</div> 

하지만 내 주요 질문은 .OrderBy 아무것도에게 내가 동의하지 않는 이유 그걸로가는거야? 이것은 람다를 사용하는 부적절한 방법입니까? 그밖에 어떻게 할 수 있습니까?

꽤 몇 가지 튜토리얼을 발견했지만 그들 중 누구도 엔터티 프레임 워크 모델을 정렬 다루는 보이지 않는다.

감사합니다. 감사합니다.

EDIT (고정) :

컨트롤러 :

public ViewResult Entries(string Specialty, string sortOrder, int page = 1) 
    { 
     //ViewBag.CurrentSort = sortOrder; 

     //sortOrder = String.IsNullOrEmpty(sortOrder) ? "TimeStamp" : sortOrder; 

     var Query = repository.Entries 
      .Where(p => Specialty == null || p.Sub == Specialty); 

     switch (sortOrder) 
     { 
      default: 
       Query = Query.OrderByDescending(p => p.TimeStamp); 
       break; 

      case "Case": 
       Query = Query.OrderBy(p => p.Case); 
       break; 

      case "Timestamp": 
       Query = Query.OrderBy(p => p.TimeStamp); 
       break; 

      case "Origin": 
       Query = Query.OrderBy(p => p.Origin); 
       break; 

      case "AssignedTo": 
       Query = Query.OrderBy(p => p.AssignedTo); 
       break; 

      case "AssignedBy": 
       Query = Query.OrderBy(p => p.AssignedBy); 
       break; 
     } 

     EntryListViewModel model = new EntryListViewModel 
     { 
      Entry = Query 
      //.Where(p => Specialty == null || p.Sub == Specialty) 
      //.OrderBy(p => sortOrder) 
      .Skip((page - 1) * pagesize) 
      .Take(pagesize), 
      PagingInfo = new PagingInfo 
      { 
       CurrentPage = page, 
       ItemsPerPage = pagesize, 
       TotalItems = Specialty == null ? 
        Query.Count() : 
        Query.Where(p => p.Sub == Specialty).Count() 
      }, 
      _SortOrder = sortOrder, 
      _CurrentCategory = Specialty 
     }; 


     return View(model); 
    } 

가 나는 또한 페이지 번호를 유지하면서 정렬을 수행 할 수있는 HTML 도우미 클래스를 작성했다. 아직 일하고 있지만 지금은 실제로 진전을 이루고 있습니다, 감사합니다!

답변

1

OrderBy 기능 작업이 개체의 속성을 반환하는 람다 식을 기대하고 문자열에 던져하려는 것입니다 방법. (이 안된하지만 당신에게 아이디어를 제공해야합니다) :이 쿼리가 비효율적이라고 생각하면

var query = repository.Entries 
         .Where(p => Specialty == null || p.Sub == Specialty); 

switch (sortOrder) 
{ 
    case "Case": 
     query = query.OrderBy(p => p.Case); 
     break; 

    case "Timestamp": 
     query = query.OrderBy(p => p.TimeStamp); 
     break; 

    case "Origin": 
     query = query.OrderBy(p => p.Origin); 
     break; 
**SNIP** 

var Entry = query.Skip((page - 1) * pagesize) 
        .Take(pagesize) 
        .ToList() //You probably need this here 

걱정하지 마십시오을, 덕분에 당신이 원하는 것을 할 수있는 한 가지 방법은 다시 구조를이 같은 코드는 지연 실행을 사용하면 결과를 구체화 할 때까지 데이터베이스가 실제로 쿼리가 아닙니다. ToList()