序列化包含StateServer的linq2sql对象的对象

时间:2011-10-06 11:13:07

标签: c# .net asp.net linq-to-sql serialization

我目前正在尝试为使用SessionState = Stateserver的服务器上托管的webproject序列化对象。

我将对象标记为[Serializable],但该对象包含一个对象,该对象是LINQ2SQL DataContext的一部分。我已经读过可以使用DataContractSerializer序列化这个序列,但是在哪里这样做是正确的?

我是否只需要实现ISerializeable并在GetObjectData()函数中序列化我的NodeObject并将其添加到SerializationInfo?关于好方法的任何一个想法吗?

2 个答案:

答案 0 :(得分:0)

请找到以下链接。理解[Serializable] VS DataContractSerializer之间的区别会很有帮助。请根据您的适用性进行实施,因为您的项目没有太大差异。

http://www.danrigsby.com/blog/index.php/2008/03/07/xmlserializer-vs-datacontractserializer-serialization-in-wcf/

答案 1 :(得分:0)

现在完成它。我将包含Linqobject的对象标记为[Serializable]并包含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 ) );
                }
            }
        }
    } 

需要包含在反序列化中的Ctor看起来像这样:

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 );
                    }
                }
            }
}