WCF中具有List(Of Object)的对象。添加到Object时,获取NullReferenceException

时间:2012-09-13 17:03:50

标签: vb.net wcf datacontract

我有一个DataContract:

<DataContract()> _
Public Class PrivateProfile
 ' This member is serialized.
<DataMember()> _
Public UserAccount As UserAccount
<DataMember()> _
Public ProfileName As String = ""
<DataMember()> _
Public Birthday As Date?
<DataMember()> _
Public Gender As Int16 = 0
<DataMember()> _
Public AboutMe As String = ""
<DataMember()> _
Public Locations As New List(Of Location)
<DataMember()> _
Public Contacts As New List(Of Contact)
End Class

联系人是:

<DataContract()> _
Public Class Contact


' This member is serialized.
<DataMember()> _
Public Value As String
<DataMember()> _
Public ContactTypes_ContactTypeId As Int16
<DataMember()> _
Public PrivatePs As New List(Of PrivateProfile)


End Class

在客户端我使用以下代码:

Dim svcProfile As New svcProfiles.ProfilesClient
.....

Dim pprofile As New svcProfiles.PrivateProfile
.....

Dim co As New svcProfiles.Contact

        co.Value = "34234234234"
        co.ContactTypes_ContactTypeId = 1

        pprofile.Contacts.Add(co)

一旦我将联系人添加到配置文件(最后一行),我就会得到一个NullReferenceException。 联系人总是什么都没有,但我不知道为什么。

任何想法......用Google搜索了很多......

修改 当我在wcf实现(服务器)端运行相同的情况时,我遇到了同样的问题:

If pprofile.Contacts.Count > 0 Then 

    Dim co As New contracts.Contact 

    For Each co In pprofile.Contacts 

        Dim con As New ef.Contact()

        con.ContactTypes_ContactTypeId = co.ContactTypes_ContactTypeId 
        con.Value = co.Value 
        con.PrivatePs.Add(pp) 
        context.Add(con) 

    Next 

    context.SaveChanges() 

End If 

1 个答案:

答案 0 :(得分:0)

我怀疑从您的服务生成的代理类是排除New关键字,只是设置属性类型。您应该能够通过显式实例化它来在调用代码中修复它:

Dim con As New ef.Contact()

con.ContactTypes_ContactTypeId = co.ContactTypes_ContactTypeId 
con.Value = co.Value 
con.PrivatePs = New PrivatePs()
con.PrivatePs.Add(pp) 
context.Add(con) 

如果您正在使用实体框架,您可能需要检查他们在导航属性的封面下生成的修正代码,以确保它们可以正确同步。