blog.mha.dk
The on-line blog of Michael Holm Andersen

Clean copy of LinqToSQL Entity object

Monday, 28 November 2011 09:53 by mha

Often you need to make a copy of a LinqToSQL (Entity) Object with all the values intact. For some reason the .NET framework does not have a method for this.

However the below code will make a “clean copy” of a LinqToSQL object.

// Instanciate new object and copy all properties from old Bill ("clean" copy)
Bill billNew = (Bill)Entity.Copy(billOld, new Bill());

And the method actually doing the work, looks like this:

public static class Entity
{
    /// <summary>
    /// Copies an LinqToSQL entity object ("clean" copy)
    /// </summary>
    /// <param name="source">Source Entity object</param>
    /// <param name="destination">Destination Entity object</param>
    /// <returns>Destination Entity object with all properties copied from Source object</returns>
    public static object Copy(object source, object destination)
    {
 
        System.Reflection.PropertyInfo[] sourceProps = source.GetType().GetProperties();
        System.Reflection.PropertyInfo[] destinationProps = destination.GetType().GetProperties();
 
        foreach (System.Reflection.PropertyInfo sourceProp in sourceProps)
        {
            ColumnAttribute column = Attribute.GetCustomAttribute(sourceProp, typeof(ColumnAttribute)) as ColumnAttribute;
 
            if (column != null && !column.IsPrimaryKey)
            {
                foreach (System.Reflection.PropertyInfo destinationProp in destinationProps)
                {
                    if (sourceProp.Name == destinationProp.Name && destinationProp.CanWrite)
                    {
                        destinationProp.SetValue(destination, sourceProp.GetValue(source, null), null);
                        break;
                    }
                }
            }
        }
 
        return destination;
    }
}
Categories:   C# | LINQ
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed
Comments are closed