2014-01-28 35 views
1

我正在嘗試按照此頁面(http://www.asp.net/mvc/tutorials/mvc-5/introduction/adding-search)中的說明操作,以瞭解如何使用網站的下拉列表創建搜索頁面。但似乎無法得到下拉列表。它不斷給我這個錯誤:System.ArgumentException:DbSortClause表達式必須具有類似順序的類型。參數名稱:鍵

System.ArgumentException: DbSortClause expressions must have a type that is order comparable. Parameter name: key

的問題是:CountryList.AddRange(CountryQry.Distinct());

搜索控制器:::

public ActionResult Index(string location, string searchString) 
    { 

     var CountryList = new List<Country>(); 

     var CountryQry = from d in db.Stuffs 
         orderby d.Country 
         select d.Country; 

     CountryList.AddRange(CountryQry.Distinct()); 
     ViewBag.location = new SelectList(CountryList); 

     var stuff = from m in db.Stuffs 
        select m; 

     if (!String.IsNullOrEmpty(searchString)) 
     { 
      stuff = stuff.Where(s => s.stuffName.Contains(searchString)); 
     } 

     if (!String.IsNullOrEmpty(location)) 
     { 
      stuff = stuff.Where(x => x.Country.countryName == location); 
     } 


     return View(stuff); 
    } 

VIEW :::

<form> 
     @using (Html.BeginForm("Index","Search",FormMethod.Get)){ 
       @Html.TextBox("SearchString", new { placeholder = "text" }) 
       @Html.DropDownList("location", "All")  
     } 
    </form> 

型號:::(這是從數據庫中自動生成)

public partial class Stuff 
{ 
    public string stuffId { get; set; } 
    public string stuffName { get; set; } 
    public string countryId { get; set; } 

    public virtual Country Country { get; set; } 
} 

我的C#知識是非常有限的,因此,我希望有人可以幫助我。 任何幫助表示讚賞!謝謝!

回答

2

該錯誤告訴您,Distinct方法需要比較Country對象的標準。您的Country類是一個複雜的類,它可能具有多個屬性,並且不實現接口IComparer。該接口聲明瞭一個用於比較兩個對象的方法,Distinct方法使用該方法來確定兩個對象是否「相等」。

您應該在Country類中實現IComparer/IComparable接口。

假設你Country類具有相似的結構(關於屬性),你可以做這樣的事情(這兩個國家都是根據自己的名字相提並論,但你可以很容易地改變比較屬性):

public class Country : IComparer 
{ 
    public string Name { get; set; } 
    public string Capital { get; set; } 
    public int Population { get; set; } 

    int IComparer.Compare(object a, object b) 
    { 
     Country c1=(Country)a; 
     Country c2=(Country)b; 

     if (c1.Name < c2.Name) 
      return 1; 

     if (c1.Name > c2.Name) 
      return -1; 

     else 
      return 0; 
    } 
} 

編輯:可能需要IEqualityComparer接口而不是IComparer

另一個編輯:圍繞這一切的一個方法是使用:

var uniqueCountries = CountryQry.GroupBy(c => c.Name).Select(g => g.FirstOrDefault()); 
+0

使用 「CountryQry」 沒有工作。但是,如果我用「db.Countries」取代它,它就會起作用......它只是不綁定「Stuff」和「Country」。至少它不會給我一個錯誤。感謝您的幫助! – jannn

+0

當涉及到Linq to Entity時,此答案不起作用。 IComparer和IEqualityComparer實現返回相同的錯誤。您需要指定對象的基礎屬性。 –

相關問題