2014-10-08 225 views
1

我似乎無法弄清楚這一點,我對MVC模型並不陌生,但也許我的大腦只是疲憊不堪。Linq從列表中選擇

視圖模型

Public Class CategoriesViewModel 
    Public Property Categories As List(Of cihCategoryOrgDef) 
    Public Property Category As cihCategoryOrgDef 
    Public Property SelectedItem As String 

    Public Sub New(organizationId As Guid, codId As Guid) 
     Categories = lists.organizationClubCategories 
     Category = From x In Categories 
        Where x.codId = codId 
        Select x 
    End Sub 
    End Class 

CategoriesController

Function Edit(codId As Guid) As ActionResult 
     Dim model As CategoriesViewModel = New CategoriesViewModel(ZenCommon.CurrentOrgId, codId) 


     Return View(model) 
    End Function 

當我運行它,我得到一個 「無效強制轉換異常」 的Category = From x....

Unable to cast object of type 'WhereSelectListIterator`2[Library.cihCategoryOrgDef,Library.cihCategoryOrgDef]' to type 'Library.cihCategoryOrgDef'. 

我試圖在我的View中使用一個Category。所以我可以爲該特定類別編輯一個頁面。我是否全部錯了?

回答

1

由於Category單個類別,您需要確保您的LINQ返回單個結果。如果你確保查詢只會返回一個值,使用SingleOrDefault

Category = (From x In Categories 
      Where x.codId = codId 
      Select x).SingleOrDefault() 

如果你的查詢可以比一個結果返回更多,你只需要採取的第一個結果是,使用FirstOrDefault

Category = (From x In Categories 
      Where x.codId = codId 
      Select x).FirstOrDefault() 
1

你的選擇實際上會返回一個集合,這就是爲什麼你會得到無效的轉換異常。要獲得只有一個項目,你需要這樣的東西(對不起,我不太熟悉VB,所以這裏是C#代碼):

Category = (From x In Categories 
       Where x.codId = codId 
       Select x).DefaultIfEmpty(null).FirstOrDefault();