2014-10-08 171 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();