Get primitive, complex, ArrayEnumerable types

I have a separate class for each of my database entities, and when I create an object of my class to reference the properties of the class, it returns a circular reference that contains the properties of other objects that are linked via FK ... to remove the circular reference, I I want to first make a copy of the object through a copy of the "context proxy object", and then get the primitive, complex, arrayEnumerable types of this object and remove these types from the object, and then return the web service object ....

+3
source share
1 answer

Sounds like a recursive shallow clone. I used the following, but only on one level.

public static class EntityBaseExtensions
{
    /// <summary>
    /// Description:    Creates a non-recursive shallow copy of an entity, only including public instance properties decorated with ColumnAttribute.
    ///                 This will return an object without entity references.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="source"></param>
    /// <returns>A non-recursive shallow copy of a LINQ entity</returns>
    public static T ShallowClone<T>(this T source) where T : EntityBaseClass
    {
        // create an object to copy values into
        T destination = Activator.CreateInstance<T>();

        // get source and destination property infos for all public instance
        PropertyInfo[] sourcePropInfos = source.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
        PropertyInfo[] destinationPropInfos = source.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);

        foreach (PropertyInfo sourcePropInfo in sourcePropInfos)
        {
            if (Attribute.GetCustomAttribute(sourcePropInfo, typeof(ColumnAttribute), false) != null)
            {
                PropertyInfo destPropInfo = destinationPropInfos.Where(pi => pi.Name == sourcePropInfo.Name).First();

                destPropInfo.SetValue(destination, sourcePropInfo.GetValue(source, null), null);
            }
        }

        return destination;
    }

}
0
source

Source: https://habr.com/ru/post/1744455/


All Articles