Reputation: 637
Im using reflection to get data dynamically (Entity types are defined at runtime). Im currently returning a single object whenever my currentObject hasn't 1:N relationships (via "First" generic method reflection implementation), but I need to get also the 1:N childs, that are EntityCollection< T >.
var valoresp = getFilho(pai, filho, raizAtual);
if (valoresp == null)
return new object();
if (!filho.A_Ocorrencia_Tabela.Contains("1:N"))
{
var firstMethod = typeof(Enumerable).GetMethods().Single(method => method.Name == "First"
&& method.IsStatic && method.GetParameters().Length == 1);
var interfaceImplementation = MethodResolver.GetImplementationOfInterface(valoresp.GetType(),
firstMethod.GetParameters().First().ParameterType.GetGenericTypeDefinition());
var genericArgumentsTypes = interfaceImplementation.GetGenericArguments();
var genericMethod = firstMethod.MakeGenericMethod(new[] { genericArgumentsTypes[0] });
try
{
var resultado = genericMethod.Invoke(null, new[] { valoresp });
return resultado;
}
catch (Exception)
{
return new object();
}
}
else
{
if (valoresp.GetType().IsGenericType && (valoresp.GetType().GetGenericTypeDefinition() == typeof(EntityCollection<>)) )
{
//here is the problem:
var typeValoresp = valoresp as EntityCollection<object>;
}
}
The fact is my "valoresp" variable can be 480 different types of EntityCollection (thats why I won't check the type manually) (EntityCollection< table1 >, EntityCollection< Table2 > ...)
I need a List of the child objects, but couldn't find a way to convert EntityCollection to List using reflection.
Upvotes: 0
Views: 1122
Reputation: 637
Just figured out how to:
Instead of trying to cast to EntityCollection, first check if it's enumerable(since EntityCollection implements IEnumerable) and cast to Enumerable.
Then you'll be able to use Linq queries, methods, etc... And plus avoid casting to List (but you still can, since IEnumerable has .ToList() Method)
if (valoresp is IEnumerable<object>)
{
var valorEnum = valoresp as IEnumerable<object>;
...
//valorEnum.First / valorEnum.where(...) etc..
}
Upvotes: 0