Question

Let's assume that we already have the stored procedures mapped from a database via Entity Framework 6.0. I am trying to filter stored procedures by their return type and then use the return type to fill a grid via WPF.

Here is the query involved:

AssemblyName assemblyName = new AssemblyName("CT_EntityDataModel");
Assembly asm = Assembly.Load(assemblyName);
var myMethods = new ObservableCollection<MethodInfo>();
// The LINQ below can be offloaded to an ICommand for reflection using the Command pattern. If the Command pattern will be used much, it really should also be a Singleton.
var q = from t in asm.GetTypes()
        where t.IsClass && t.Namespace == "CT_EntityDataModel"
        && t.Name.Equals("CRMEntities")
        select t.GetMethods();

When I use reflection to load the stored procedures, the information I want is in the [MethodInfoInstance].ReturnType.UnderlyingSystemType. However, when I try to get more information on this UnderlyingSystemType, I get very little useful information. Here's the result of the immediate window:

j.ReturnType.UnderlyingSystemType
{Name = "ObjectResult`1" FullName = "System.Data.Entity.Core.Objects.ObjectResult`1[[CT_EntityDataModel.PROC_RE_ReadImportInvest_Result, CT_EntityDataModel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]"}
    [System.RuntimeType]: {Name = "ObjectResult`1" FullName = "System.Data.Entity.Core.Objects.ObjectResult`1[[CT_EntityDataModel.PROC_RE_ReadImportInvest_Result, CT_EntityDataModel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]"}
    base: {Name = "ObjectResult`1" FullName = "System.Data.Entity.Core.Objects.ObjectResult`1[[CT_EntityDataModel.PROC_RE_ReadImportInvest_Result, CT_EntityDataModel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]"}
    Assembly: {EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089}
    AssemblyQualifiedName: "System.Data.Entity.Core.Objects.ObjectResult`1[[CT_EntityDataModel.PROC_RE_ReadImportInvest_Result, CT_EntityDataModel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
    Attributes: Public | BeforeFieldInit
    BaseType: {Name = "ObjectResult" FullName = "System.Data.Entity.Core.Objects.ObjectResult"}
    ContainsGenericParameters: false
    DeclaringMethod: 'j.ReturnType.UnderlyingSystemType.DeclaringMethod' threw an exception of type 'System.InvalidOperationException'
    DeclaringType: null
    FullName: "System.Data.Entity.Core.Objects.ObjectResult`1[[CT_EntityDataModel.PROC_RE_ReadImportInvest_Result, CT_EntityDataModel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]"
    GenericParameterAttributes: 'j.ReturnType.UnderlyingSystemType.GenericParameterAttributes' threw an exception of type 'System.InvalidOperationException'
    GenericParameterPosition: 'j.ReturnType.UnderlyingSystemType.GenericParameterPosition' threw an exception of type 'System.InvalidOperationException'
    GenericTypeArguments: {System.Type[1]}
    GUID: {3cea792c-523d-3659-8584-7b6e3ad1678b}
    HasElementType: false
    IsAbstract: false
    IsAnsiClass: true
    IsArray: false
    IsAutoClass: false
    IsAutoLayout: true
    IsByRef: false
    IsClass: true
    IsCOMObject: false
    IsConstructedGenericType: true
    IsContextful: false
    IsEnum: false
    IsExplicitLayout: false
    IsGenericParameter: false
    IsGenericType: true
    IsGenericTypeDefinition: false
    IsImport: false
    IsInterface: false
    IsLayoutSequential: false
    IsMarshalByRef: false
    IsNested: false
    IsNestedAssembly: false
    IsNestedFamANDAssem: false
    IsNestedFamily: false
    IsNestedFamORAssem: false
    IsNestedPrivate: false
    IsNestedPublic: false
    IsNotPublic: false
    IsPointer: false
    IsPrimitive: false
    IsPublic: true
    IsSealed: false
    IsSecurityCritical: true
    IsSecuritySafeCritical: false
    IsSecurityTransparent: false
    IsSerializable: false
    IsSpecialName: false
    IsUnicodeClass: false
    IsValueType: false
    IsVisible: true
    MemberType: TypeInfo
    Module: {EntityFramework.dll}
    Namespace: "System.Data.Entity.Core.Objects"
    ReflectedType: null
    StructLayoutAttribute: {System.Runtime.InteropServices.StructLayoutAttribute}
    TypeHandle: {System.RuntimeTypeHandle}
    TypeInitializer: null
    UnderlyingSystemType: {Name = "ObjectResult`1" FullName = "System.Data.Entity.Core.Objects.ObjectResult`1[[CT_EntityDataModel.PROC_RE_ReadImportInvest_Result, CT_EntityDataModel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]"}

Is there a method on the UnderlyingSystemType or elsewhere that will allow me to get the return type?

And yes, I know the performance of reflection is horrible. Once I can figure out how to do this, I will optimize the code at the IL level. And if you tell me to use ADO.NET or something else, I will tell you that you have no idea what you are talking about. For your information, the only clean way that I would be able to get the return types directly from the database involves sys.dm_exec_describe_first_result_set_for_object, which is not included in databases prior to SQL Server 2012; moreover, dm_exec_describe_first_result_set_for_object does not provide much useful information from procedures that contain dynamic SQL.

In the worst case, I suppose I could simply use a regular expression to grab the type from the MethodInfo instance .ReturnType.UnderlyingSystemType.FullName, which looks like this:

"System.Data.Entity.Core.Objects.ObjectResult`1[[CT_EntityDataModel.PROC_RE_ReadImportInvest_Result, CT_EntityDataModel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]"

If I look at the type PROC_CT_ReadImportInvest_Result, it's definition looks like this:

namespace CT_EntityDataModel
{
    using System;

    public partial class PROC_RE_ReadImportInvest_Result
    {
        public System.DateTime dtDate1 { get; set; }
        public string txtData1 { get; set; }
    }
}

I want the "PROC_RE_ReadImportInvest_Result" part of the above FullName value. Is there a less ugly way to get this type instead of using a Regex to extract it?

Thanks, Devin

[Update (4/20/2014 at 5:56 PM PST): Here is the final code that solves this problem]:

    // If these values will be consumed by a ViewModel, then we need to use an ObservableDictionary here.
public  Dictionary<MethodInfo, Type> GetTypesDictionary()
{
    // This is for our ViewModel.
    AssemblyName assemblyName = new AssemblyName("CT_EntityDataModel");
    Assembly asm = Assembly.Load(assemblyName);
    // The LINQ below can be offloaded to an ICommand for reflection.
    var q = from t in asm.GetTypes()
            where t.IsClass && t.Namespace == "CT_EntityDataModel"
            && t.Name.Equals("CRMEntities")
            select t.GetMethods();
    // We need to filter these to only those that return a dataset.
    // q can be offloaded to an IPredicateStrategy that returns only the results that match the strategy.
    return (from i in q
            from j in i
            where j.Name.StartsWith("PROC_") && j.Name.Contains("Global")
            let methodType = j.ReturnType.UnderlyingSystemType
            where methodType.IsGenericType
            let test = j.ReturnType.UnderlyingSystemType.GetGenericArguments()
            where test.Length > 0
            select j).ToDictionary(j => j, j => j.ReturnType.UnderlyingSystemType.GetGenericArguments()[0]);
// We can use a Strategy pattern to encapsulate the ".Name.StartsWith" logic.
// This would make an interesting extension method. 
}
Was it helpful?

Solution

It seems that you are getting generic proxy object. You could try something like this:

var methodType = [MethodInfoInstance].ReturnType.UnderlyingSystemType;

if(methodType.IsGenericType)
{
    methodType = methodType.GetGenericArguments()[0];
}

PS. I am writing this from top of my head, so forgive me if there are some syntax errors.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top