2011-10-06 100 views
3

我目前正在嘗試爲使用SessionState = Stateserver的服務器上承載的Web項目序列化一個對象。包含StateServer的linq2sql對象的序列化對象

我將該對象標記爲[Serializable],但該對象包含一個屬於LINQ2SQL DataContext的對象。我已經讀過,可以用DataContractSerializer將這個序列化,但是在哪裏可以做到這一點?

我只需要執行ISerializeable並在GetObjectData()函數中序列化我的NodeObject並將其添加到SerializationInfo?任何一個關於一個好方法的想法?

回答

0

現在就完成它。我用[Serializable]標記了包含Linqobject的對象,幷包含了ISerializable接口。 DBOItem是我LinqObject

public void GetObjectData(SerializationInfo info, StreamingContext context) 
    { 
     PropertyInfo[] infos = this.DBOItem.GetType().GetProperties(); 
     foreach (PropertyInfo pi in infos) 
     { 
      bool isAssociation = false; 
      foreach (object obj in pi.GetCustomAttributes(true)) 
      { 
       if (obj.GetType() == typeof(System.Data.Linq.Mapping.AssociationAttribute)) 
       { isAssociation = true; break; } 
      } 
      if (!isAssociation) 
      { 
       if (pi.GetValue(this.DBOItem, null) != null) 
       { 
        info.AddValue(pi.Name, pi.GetValue(this.DBOItem, null)); 
       } 
      } 
     } 
    } 

的構造函數需要被列入deserialisation看起來是這樣的:

protected BusinessObjectBase(SerializationInfo info, StreamingContext context) 
{ 
    this.DBOItem = new T(); 
      PropertyInfo[] properties = this.DBOItem.GetType().GetProperties(); 
      SerializationInfoEnumerator enumerator = info.GetEnumerator(); 

      while (enumerator.MoveNext()) 
      { 
       SerializationEntry se = enumerator.Current; 
       foreach (PropertyInfo pi in properties) 
       { 
        if (pi.Name == se.Name) 
        { 
         pi.SetValue(this.DBOItem, info.GetValue(se.Name, pi.PropertyType), null); 
        } 
       } 
      } 
}