Skip to content

Instantly share code, notes, and snippets.

@AlbertoMonteiro
Created April 18, 2012 15:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlbertoMonteiro/2414298 to your computer and use it in GitHub Desktop.
Save AlbertoMonteiro/2414298 to your computer and use it in GitHub Desktop.
Proxy remover from objects returned by NHibernate
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
namespace Nash.Core
{
public class NHibernateProxyRemover
{
public static T From<T>(T objeto)
{
var type = typeof(T);
var retorno = Activator.CreateInstance(type);
foreach (var propertyInfo in type.GetProperties())
{
if ((IsEnum(propertyInfo) && IsPrimitive(propertyInfo)) || IsString(propertyInfo))
continue;
var value = propertyInfo.GetValue(objeto, null);
var valueType = value.GetType();
if (ImplementsIEnumerable(propertyInfo))
{
var genericArgument = propertyInfo.PropertyType.GetGenericArguments()[0];
var type1 = typeof(List<>);
var makeGenericType = type1.MakeGenericType(propertyInfo.PropertyType.GetGenericArguments());
var instance = (IList)Activator.CreateInstance(makeGenericType);
foreach (var obj in (IEnumerable)value)
{
var desproxyaONego = Desproxiador(obj, genericArgument);
instance.Add(desproxyaONego);
}
propertyInfo.SetValue(retorno, instance, null);
continue;
}
if (valueType.Name.Contains("Proxy"))
{
var desproxyaONego = Desproxiador(value, valueType.BaseType);
propertyInfo.SetValue(retorno, desproxyaONego, null);
}
}
return (T)retorno;
}
private static bool ImplementsIEnumerable(PropertyInfo propertyInfo)
{
return propertyInfo.PropertyType.GetInterface("IEnumerable") != null;
}
private static bool IsString(PropertyInfo propertyInfo)
{
return propertyInfo.PropertyType == typeof(string);
}
private static bool IsPrimitive(PropertyInfo propertyInfo)
{
return propertyInfo.PropertyType.IsPrimitive;
}
private static bool IsEnum(PropertyInfo propertyInfo)
{
return propertyInfo.PropertyType.IsEnum;
}
private static object Desproxiador(object objeto, Type baseType)
{
var retornavel = Activator.CreateInstance(baseType);
foreach (var propertyInfo in baseType.GetProperties())
{
var value = propertyInfo.GetValue(objeto, null);
if (value == null)
continue;
var valueType = value.GetType();
if (valueType.Name.Contains("Proxy"))
value = Desproxiador(value, valueType.BaseType);
propertyInfo.SetValue(retornavel, value, null);
}
return retornavel;
}
}
}
@fabiodiluca
Copy link

Amigo,fiz um que conserva os Ids dos proxies e é recursivo. Está um pouco mais compacto: https://github.com/fabiodiluca/NHibernateUnProxyExtension/blob/master/NHibernateUnProxyHelperExtension.cs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment