Click here to Skip to main content
15,893,594 members
Articles / Web Development / XHTML

An ASP.NET Data Layer Base Class for LINQ Disconnected Mode

Rate me:
Please Sign up or sign in to vote.
4.73/5 (21 votes)
14 Mar 2009CPOL6 min read 81.3K   1.1K   68  
Quickly and easily implement your LINQ Data Layer with this abstract class
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;

namespace DeverMind
{
    public class EntityDetacher<T>
    {
        //detach a LINQ entity from it's previous datacontext by serialization / deserialization
        static public T Detach(T item)
        {
            string detachedProp = Serialize(item);
            return (T) Deserialize(typeof (T), detachedProp);
        }

        static private string Serialize(object value)
        {
            if (value.GetType() == typeof (string))
                return value.ToString();

            var stringWriter = new StringWriter();
            using (XmlWriter writer = XmlWriter.Create(stringWriter))
            {
                var serializer = new
                    DataContractSerializer(value.GetType());
                serializer.WriteObject(writer, value);
            }

            return stringWriter.ToString();
        }

        static  private object Deserialize(Type type, string serializedValue)
        {
            if (type == typeof (string))
                return serializedValue;

            using (var stringReader = new StringReader(serializedValue))
            {
                using (XmlReader reader = XmlReader.Create(stringReader))
                {
                    var serializer =
                        new DataContractSerializer((type));

                    object deserializedValue = serializer.ReadObject(reader);

                    return deserializedValue;
                }
            }
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Chief Technology Officer Lobstersoft
Germany Germany
Adrian Grigore holds a German diploma in Computer sciences from the University of Würzburg, Germany.

He founded Lobstersoft early during his studies and has since then released several commercially successful game titles. All of these games were created using Adrian's custom build game engine.

In addition to object-oriented software design in C+ and C#, Adrian's main areas of expertise are ASP.NET, Perl and XML/XSLT.

Apart from leading Lobstersoft, Adrian also works as a freelance software development consultant.

Comments and Discussions