A Simple Method to Clone an EntityObject

Written by Brad Foley on. Posted in .NET Development

 

I’ve just come across a problem where I needed to clone an Entity and add the duplicate value to the context only changing one property. I don’t know where I got this from originally, but I’ve made tweaks to it, and it works like a charm.

public static EntityObject Clone(EntityObject entity)
        {
            var type = entity.GetType();
            var clone = Activator.CreateInstance(type);

            foreach (var property in type.GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.SetProperty))
            {
                if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(EntityReference<>)) continue;
                if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(EntityCollection<>)) continue;
                if (property.PropertyType.IsSubclassOf(typeof(EntityObject))) continue;

                if (property.CanWrite)
                {
                    property.SetValue(clone, property.GetValue(entity, null), null);
                }
            }

            return (EntityObject)clone;
        } 

This is a simple method that could even be made an extension method. Enjoy!

Tags: , ,

Trackback from your site.

Leave a comment