I just came 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!
Leave a Comment