序列化一个包含linq2sql对象的对象

本文关键字:对象 包含 linq2sql 一个 序列化 | 更新日期: 2023-09-27 18:10:30

我目前正在尝试序列化一个web项目的对象,该项目托管在使用SessionState = Stateserver的服务器上。

我将对象标记为[Serializable],但该对象包含一个属于LINQ2SQL DataContext的对象。我已经读到可以用DataContractSerializer序列化这个,但是正确的地方在哪里?

我只需要实现ISerializeable和序列化我的NodeObject内GetObjectData()函数,并将其添加到SerializationInfo ?谁有什么好的方法?

序列化一个包含linq2sql对象的对象

请看下面的链接。理解[Serializable]和DataContractSerializer之间的区别将会很有帮助。请根据您的适合程度来实施,因为您的项目没有太大的差异。

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

现在就做。我用[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 ) );
                }
            }
        }
    } 

反序列化需要包含的tor如下所示:

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 );
                    }
                }
            }
}
相关文章: