Canalblog
Editer l'article Suivre ce blog Administration + Créer mon blog
Publicité
asp.net
Publicité
Archives
26 juin 2009

LINQ To SQL issue when serializing in the viewstate

After having implemented LINQ DTO with relations, using the codeplex L2ST4 templates, I got an error when seriallizing the DTO to the viewstate. The problem was about th serialization of a relation, implemented as an entityset in the DTO. The problem was the ViewState Serializer did not recognise the entityset.

The solution: a workaround to serialize myself the DTO before passing it to the ViewState serializer, and reverse the process for deserialization.

First, create a Serializer Helper

Secondly, create a generic decorator for LINQ To SQL Entities, serializing/deserializing:

[Serializable]
    public class SViewState<T> : System.Runtime.Serialization.ISerializable where T:class 
    {
        public SViewState() { }
        public SViewState(T obj)
        {
            ViewState = (T)obj;
        }
        private String _xml;
      
        public String SObject
        {
            get
            {
                _xml = ViewState.GetType().FullName + "<>" +SerializeHelper.SerializeXml( ViewState) ;
                return _xml;
            }
            set
            {
                int index = value.IndexOf("##");
                string typeName = value.Substring(0, index);
                _xml = value.Substring(index + 2);
                Type typ = Type.GetType(typeName);
                ViewState = (T)SerializeHelper.DeserializeXMl(typeof(T), _xml);
            }
        }
        [NonSerialized]
        private T _viewState = null;
        public T ViewState { get { return _viewState; } set { _viewState = value; } }

        protected SViewState(SerializationInfo info, StreamingContext context)
          {
            ViewState = (T)SerializeHelper.DeserializeXMl(typeof(T), info.GetString("_xml"));
          }
        [SecurityPermission(SecurityAction.Demand,
        SerializationFormatter =true)]

        public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
          {
              info.AddValue("_xml", SerializeHelper.SerializeXml(ViewState));
          }

    }

Thirdly, implement a ViewState accessor :

private Contract CurrentContract
        {
            get
            {
                return ((SViewState<Contract>)ViewState["CurrentContract"]).ViewState ;
            }
            set
            {
                ViewState["CurrentContract"] = new SViewState<Contract>( value) ;
            }
        }

And That's it.

Enjoy!

Publicité
Publicité
Commentaires
C
Thank you so much! This has saved me hours!
Publicité