WCF反序列化正在丢失子集合

本文关键字:子集合 反序列化 WCF | 更新日期: 2023-09-27 17:57:25

我几天来一直在寻找以下问题的答案,到目前为止没有任何运气,非常感谢您的帮助。

免责声明:WCF和EntityFramework对我来说是新概念,但.NET、c#、web服务、对象关系映射概念肯定不是。

我继承了一个带有客户端应用程序的应用程序,该应用程序使用WCF服务来检索和保存一个"Matter"对象,该对象包含与"CaseNotesLog"对象的一对多关系。

客户端可以成功地检索具有0、1或多个子CaseNotesLog对象的某些Matters,还可以成功地保存具有添加、更新或删除的CaseNotesLog对象的Matters。

然而,到目前为止,似乎有一组Matters,其中的子CaseNotesLog对象可以成功读取,但即使根本没有更改,也无法保存。

本质上,当保存Matter对象时,WCF上的反序列化过程会丢失子CaseNotesLog条目。

澄清:

  1. 读取
    1. Matter记录在数据库中具有1个CaseNotesLog子记录
    2. 它已成功转换为服务器上具有子CaseNotesLog对象的EntityFramework Matter对象
    3. 它在WCF服务中成功地序列化/反序列化,并在客户端正确地使用子CaseNotesLog填充Matter对象
  2. 保存
    1. 具有子CaseNotesLog对象的客户端Matter对象"离开"客户端应用程序
    2. 它被序列化以通过WCF服务传递回服务器
    3. 查看跟踪日志,此序列化包含子CaseNotesLog
    4. 该对象在服务器端被反序列化
    5. 通过在entityframework Matter对象的Setter代码中添加跟踪语句,我可以观察到CaseNotesLog子级被正确地放置在父级Matter中
    6. 但是一旦调用Getter功能,集合就为空

就好像RelationshipManager集合正在其他地方重置一样。

最终的结果是,带有子CaseNotesLog对象的Matter对象将我的代码留在客户端,但尽管当我在服务器端检查对象的状态时,它看起来正在正确地序列化/反序列化,但子记录已经消失。

为了进行检查,我在entityframework类中添加了一些代码,以保持子集合应该有多大的独立计数。当设置CaseNotesLog集合时,它在set操作期间被设置为1,而当在Get过程中检索CaseNotesLog集时,它仍保持为1,即使集合已被清空。

雪上加霜*这并不适用于所有事项,有些似乎有效,有些则无效*这似乎并不适用于所有类型的子对象——其他集合似乎可以工作。

WCF服务以及其他方法实现了以下内容:

[ServiceContract]
public interface IMattersService
{
    ...
    [OperationContract]
    Matter ReadMatter(int matterID);
    ...
    [OperationContract]
    void SaveMatter(Matter matter);
    ...
    }
}

其实现方式如下:

public class MattersService : IMattersService
{
   ...
   public Matter ReadMatter(int matterID)
   {
       using (var repo = new MatterRepository())
       {
           try
           {
               return repo.ReadMatter(matterID);
           }
           catch (Exception ex)
           {
               Logger.Write(ex, "Error", 0);
               throw;
           }
       }
   }
   ...
   public void SaveMatter(Matter matter)
   {
       Trace.WriteLine(matter.CaseNotesLogs.Count);
       using (var repo = new MatterRepository())
       {
           try
           {
               repo.SaveMatter(matter);
           }
           catch (Exception ex)
           {
               Logger.Write(ex, "Error", 0);
               throw;
           }
       }
   }
   ...
}

Matter是EntityFramework生成的类:

/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmEntityTypeAttribute(NamespaceName="EDDSolutionsLtd.Services.Data", Name="Matter")]
[Serializable()]
[DataContractAttribute(IsReference=true)]
public partial class Matter : EntityObject
{
    ...
    /// <summary>
    /// No Metadata Documentation available.
    /// </summary>
    [XmlIgnoreAttribute()]
    [SoapIgnoreAttribute()]
    [DataMemberAttribute()]
    [EdmRelationshipNavigationPropertyAttribute("EDDSolutionsLtd.Services.Data", "MatterCaseNotesLog", "CaseNotesLog")]
    public EntityCollection<CaseNotesLog> CaseNotesLogs
    {
        get
        {
            return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<CaseNotesLog>("EDDSolutionsLtd.Services.Data.MatterCaseNotesLog", "CaseNotesLog");
        }
        set
        {
            if ((value != null))
            {
                ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<CaseNotesLog>("EDDSolutionsLtd.Services.Data.MatterCaseNotesLog", "CaseNotesLog", value);
            }
        }
    }
    ...
}

我添加了一些日志的损坏版本:

public int CheckCaseNotesLogsCount { get; set; }
public EntityCollection<CaseNotesLog> CheckCaseNotesLogs { get; set; }
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[XmlIgnoreAttribute()]
[SoapIgnoreAttribute()]
[DataMemberAttribute()]
[EdmRelationshipNavigationPropertyAttribute("EDDSolutionsLtd.Services.Data", "MatterCaseNotesLog", "CaseNotesLog")]
public EntityCollection<CaseNotesLog> CaseNotesLogs
{
    get
    {
        if (CheckCaseNotesLogs != null)
        {
            Trace.WriteLine("GET ACTUAL CheckCaseNotesLogs[" + CheckCaseNotesLogs.Count + "]");
        }
        Trace.WriteLine("GET ACTUAL CheckCaseNotesLogsCount[" + CheckCaseNotesLogsCount + "]");
        StackTrace st = new StackTrace();
        int i = ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<CaseNotesLog>("EDDSolutionsLtd.Services.Data.MatterCaseNotesLog", "CaseNotesLog").Count;
        Trace.WriteLine("GET ACTUAL value[" + i + "]");
        Trace.WriteLine(st.ToString());
        return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<CaseNotesLog>("EDDSolutionsLtd.Services.Data.MatterCaseNotesLog", "CaseNotesLog");
    }
    set
    {
        if ((value != null))
        {
            CheckCaseNotesLogs = value;
            CheckCaseNotesLogsCount = value.Count;
            Trace.WriteLine("SET ACTUAL value[" + value.Count + "]");
            ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<CaseNotesLog>("EDDSolutionsLtd.Services.Data.MatterCaseNotesLog", "CaseNotesLog", value);
            Trace.WriteLine("SET ACTUAL Property value[" + this.CaseNotesLogs.Count + "]");
        }
        else
        {
           Trace.WriteLine("SET NULL Value");
        }
    }
}

这是Wcf服务收到的Soap消息片段,显示存在子CaseNotesLog记录。

<E2ETraceEvent xmlns="http://schemas.microsoft.com/2004/06/E2ETraceEvent">
  <System xmlns="http://schemas.microsoft.com/2004/06/windows/eventlog/system">
    <EventID>0</EventID>
    <Type>3</Type>
    <SubType Name="Information">0</SubType>
    <Level>8</Level>
    <TimeCreated SystemTime="2011-05-19T22:49:34.7968750Z" />
    <Source Name="System.ServiceModel.MessageLogging" />
    <Correlation ActivityID="{fa25d214-04e9-4b16-8ae8-3de7b9a12bc6}" />
    <Execution ProcessName="WebDev.WebServer40" ProcessID="2332" ThreadID="13" />
    <Channel />
    <Computer>EDD-MERCURY</Computer>
  </System>
  <ApplicationData>
    <TraceData>
      <DataItem>
        <MessageLogTraceRecord Time="2011-05-19T23:49:34.7812500+01:00"
        Source="ServiceLevelReceiveRequest"
        Type="System.ServiceModel.Channels.BufferedMessage"
            xmlns="http://schemas.microsoft.com/2004/06/ServiceModel/Management/MessageTrace">
          <HttpRequest>
            <Method>POST</Method>
            <QueryString></QueryString>
            <WebHeaders>
              <Content-Length>142631</Content-Length>
              <Content-Type>application/soap+xml;
              charset=utf-8</Content-Type>
              <Expect>100-continue</Expect>
              <Host>localhost:58080</Host>
              <VsDebuggerCausalityData>
              uIDPo7kHl/h9zQNAkghvTvB5/u8AAAAAuoDOged1MUm+UmudC0H6u3k/74R6jUpIn/o2sS4KNxYACQAA</VsDebuggerCausalityData>
            </WebHeaders>
          </HttpRequest>
          <s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope"
          xmlns:a="http://www.w3.org/2005/08/addressing">
            <s:Header>
              <a:Action s:mustUnderstand="1">
              http://tempuri.org/IMattersService/SaveMatter</a:Action>
              <a:MessageID>
              urn:uuid:f1d751a7-1012-4268-b7da-87a12cf6d14f</a:MessageID>
              <ActivityId CorrelationId="4f53460f-8880-4b6e-aa66-557fa90d4ae3"
              xmlns="http://schemas.microsoft.com/2004/09/ServiceModel/Diagnostics">
              fa25d214-04e9-4b16-8ae8-3de7b9a12bc6</ActivityId>
              <a:ReplyTo>
                <a:Address>
                http://www.w3.org/2005/08/addressing/anonymous</a:Address>
              </a:ReplyTo>
              <a:To s:mustUnderstand="1">
              http://localhost:58080/MattersService.svc</a:To>
            </s:Header>
            <s:Body>
              <SaveMatter xmlns="http://tempuri.org/">
                <matter z:Id="i1"
                xmlns:b="http://schemas.datacontract.org/2004/07/EDDSolutionsLtd.Services.Data"
                xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
                xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/">
                  <EntityKey z:Id="i2"
                      xmlns="http://schemas.datacontract.org/2004/07/System.Data.Objects.DataClasses"
                  xmlns:c="http://schemas.datacontract.org/2004/07/System.Data">
                    <c:EntityContainerName>
                    EDDSolutionsLtdEntities</c:EntityContainerName>
                    <c:EntityKeyValues>
                      <c:EntityKeyMember>
                        <c:Key>ID</c:Key>
                        <c:Value i:type="d:int"
                        xmlns:d="http://www.w3.org/2001/XMLSchema">
                        180</c:Value>
                      </c:EntityKeyMember>
                    </c:EntityKeyValues>
                    <c:EntitySetName>Matters</c:EntitySetName>
                  </EntityKey>
                  <b:AllRecordsReceivedDate i:nil="true">
                  </b:AllRecordsReceivedDate>
                  <b:BeginClaimDate i:nil="true">
                  </b:BeginClaimDate>
                  ...
                  <b:CaseEmailLogs></b:CaseEmailLogs>
                  <b:CaseFileLogs></b:CaseFileLogs>
                  <b:CaseNotesLogs>
                    <b:CaseNotesLog z:Id="i3">
                      <EntityKey z:Id="i4"
                          xmlns="http://schemas.datacontract.org/2004/07/System.Data.Objects.DataClasses"
                      xmlns:c="http://schemas.datacontract.org/2004/07/System.Data">
                        <c:EntityContainerName>
                        EDDSolutionsLtdEntities</c:EntityContainerName>
                        <c:EntityKeyValues>
                          <c:EntityKeyMember>
                            <c:Key>ID</c:Key>
                            <c:Value i:type="d:int"
                            xmlns:d="http://www.w3.org/2001/XMLSchema">
                            281</c:Value>
                          </c:EntityKeyMember>
                        </c:EntityKeyValues>
                        <c:EntitySetName>
                        CaseNotesLogs</c:EntitySetName>
                      </EntityKey>
                      <b:ActivityDate>
                      2011-05-18T00:00:00</b:ActivityDate>
                      <b:Body i:nil="true"></b:Body>
                      <b:Comment>3</b:Comment>
                      <b:ContactID>608</b:ContactID>
                      <b:CreatedBy>mminns</b:CreatedBy>
                      <b:CreatedOn>
                      2011-05-19T15:25:03.923</b:CreatedOn>
                      <b:ID>281</b:ID>
                      <b:MatterId>180</b:MatterId>
                      <b:ModifiedBy>mminns</b:ModifiedBy>
                      <b:ModifiedOn>
                      2011-05-19T15:25:03.923</b:ModifiedOn>
                      <b:OriginalContactID>0</b:OriginalContactID>
                      <b:Outcome>Unknown</b:Outcome>
                      <b:Subject>1</b:Subject>
                    </b:CaseNotesLog>
                  </b:CaseNotesLogs>
                  ...
                </matter>
              </SaveMatter>
            </s:Body>
          </s:Envelope>
        </MessageLogTraceRecord>
      </DataItem>
    </TraceData>
  </ApplicationData>
</E2ETraceEvent>                  

WCF反序列化正在丢失子集合

你能为数据契约标记这个属性吗:System.Runtime.Serialization.DataContractAttribute(IsReference=true)]