简体   繁体   中英

Can't Add Model to List

I perform the following for each loop to insert models into a list:

        Dim weights = weight.Where(Function(x) x.FW_Food_ID = item.NDB_No)

        For Each i In weights
            Dim model = New Tbl_Food_Weight
            model.FW_GmWt = i.FW_GmWt
            Debug.Print("i.FW_GmWt=" + i.FW_GmWt)
            Debug.Print("model.FW_GmWt=" + model.FW_GmWt)
            model.FW_Food_ID = i.FW_Food_ID
            Debug.Print("i.FW_Food_ID=" + i.FW_Food_ID)
            Debug.Print("model.FW_Food_ID=" + model.FW_Food_ID)
            model.FW_Option = i.FW_Option
            Debug.Print("i.FW_Option=" + i.FW_Option)
            Debug.Print("model.FW_Option=" + model.FW_Option)
            model.FW_ID = i.FW_ID
            Debug.Print("i.FW_ID=" + i.FW_ID.ToString)
            Debug.Print("model.FW_ID=" + model.FW_ID.ToString)
            item.test.Add(model)
        Next

My model is as follows:

Public Class Tbl_Food_Weight

    <Key()> _
    Public Property FW_ID As Integer
    Public Property FW_Food_ID As String
    Public Property FW_Option As String
    Public Property FW_Serving_Size As String
    Public Property FW_GmWt As String

End Class

My test property is as follows:

<NotMapped()> _
Public Overridable Property test As List(Of Tbl_Food_Weight)

The output that I get is:

i.FW_GmWt=250
model.FW_GmWt=250
i.FW_Food_ID=12695
model.FW_Food_ID=12695
i.FW_Option=1
model.FW_Option=1
i.FW_ID=4481
model.FW_ID=4481
A first chance exception of type 'System.NullReferenceException' occurred in MyBlog.DLL

The error occurs on this line:

item.test.Add(model)

You see, it puts in the variables, but when I go to add the model to the list, it says it's null. How can I add the model to the list of models?

Thank you.

Edit:

Item in context:

For Each item In food

            Dim weights = weight.Where(Function(x) x.FW_Food_ID = item.NDB_No)
            ... rest of code already posted above

model isn't null -- your test property is. In the constructor of whatever item is, you need to "new" your collection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM