为什么我不能在MVC中做这个Foreach?

时间:2012-10-03 12:41:19

标签: asp.net-mvc vb.net asp.net-mvc-3

这是我的控制器动作:

<EmployeeAuthorize()>
Function HRA_Table() As ActionResult

    ' get current employee's id
    Dim db1 As EmployeeDbContext = New EmployeeDbContext
    Dim user1 = db1.Tbl_Employees.Where(Function(e) e.Employee_EmailAddress = User.Identity.Name).Single()
    Dim empId = user1.Employee_ID
    Dim empSSN = user1.Employee_SSN

    Dim hra = db.Tbl_HRAs.Where(Function(x) x.SSN = empSSN)

    Return View(hra.ToList)

End Function

这是我的模特:

Public Class Tbl_HRA

    <Key()> Public Property HRA_ID() As Integer
    Public Property SSN() As String
    Public Property Height() As Double
    Public Property Weight() As Double
    Public Property Nic_EE() As String
    Public Property Nic_SP() As String
    Public Property BMI() As Double
    Public Property BP_S() As Double
    Public Property BP_D() As Double
    Public Property HDL() As Double
    Public Property LDL() As Double
    Public Property Tot_Chol() As Double
    Public Property Continine() As String
    Public Property Glucose() As Double
    Public Property Waist() As Double
    Public Property Hip() As Double
    Public Property Triglycerides() As Double
    Public Property A1C() As Double
    Public Property LDL_HDL() As Double

End Class

这是我的观点:

@ModelType IEnumerable(Of GemcoBlog.Tbl_HRA)

@Code
    Layout = Nothing
End Code

@For Each item In Model

    @item.Height

Next

我得到的错误是:

  

'Tbl_HRA'上的'Height'属性无法设置为'String'   值。您必须将此属性设置为类型的非null值   '双'。

我似乎无法理解为什么会发生此错误。我尝试根据我读过的一些文章将其更改为double,但仍然无效!

感谢您的帮助。

4 个答案:

答案 0 :(得分:0)

这篇文章可能有用 - 看起来像数据库架构的问题?此列是否在表中设置为可为空?

http://digitaltoolfactory.net/blog/2012/03/how-to-fix-yet-another-you-must-set-this-property-to-a-non-null-value-of-type-double-problem-with-entity-framework/

答案 1 :(得分:0)

我认为这会对你有所帮助

<ul>
    @For Each g As MvcApplication1.Genre In Model
        @<li>@g.Name</li>
    Next
</ul>

并且还会看到此网址以获取更多帮助

http://www.asp.net/web-pages/tutorials/basics/asp-net-web-pages-visual-basic

答案 2 :(得分:0)

看起来这可能是由这个数据库引起的。看起来他们将这些设置为varchar而不是double,这是不理想的。

答案 3 :(得分:0)

从您的评论中,表中的列似乎是varchar。因此,您的模型必须将其定义为字符串。尝试将height属性更改为如下:

 Public Property Height() As String

不幸的是,您不能直接在LINQ to SQL实现中进行类型转换。如果需要,可以投影到另一种类型(在Select子句中),但是仍然需要立即获取(context.GetTable(Of T))以使类型在数据库和模型之间等效。