locked
Reflection getValue of subclass (List) RRS feed

  • Question

  • User-1132163444 posted

    Hi, please help me,

    This how my model looks like

    public class Master
    {
       public string Name {get; set;}
       public ICollection<Detail> Details {get; set;}
    }
    public class Detail
    {
       public string Name {get; set;}
    }

    All i need is to get the actual list "Details"

    via this code 

    var list = (System.Collections.IList)info.GetValue(obj, null);

    but it says "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection. "

    btw, the "obj" parameter is an Entity object

    public void GetValues(object obj,string fieldName){ //<-- fieldName = "Details.Name"
    string[] nameParts = fieldName.Split('.');
    foreach (String part in nameParts)
                {
                    if (obj == null) { return null; }
    
                    Type type = obj.GetType();
                    PropertyInfo info = type.GetProperty(part);
                    if (info == null) { return null; }
    
                    if (info.PropertyType.Name.ToLower().Contains("collection"))
                    {
                        var list = (System.Collections.IList)info.GetValue(obj, null);
                        foreach (var item in list) //<-- this list should be the "Details" property
                        {
    
                        }
                    }
                    else {
                        obj = info.GetValue(obj, null);
                    }
                    
                }
    }


    Thanks

    Thursday, August 10, 2017 10:14 AM

Answers

  • User-1132163444 posted

    Hi, 

    just to help anyone just incase they bumped to this same problem, i was able to solved this by casting the PropertyInfo.GetValue result to IEnumerable

    var list = (IEnumerable)info.GetValue(obj, null);
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, August 11, 2017 3:02 AM

All replies

  • User1068175894 posted

    the solution is in the place you pull the obj list from the database,

    make sure you call .ToList before closing the connection

    Thursday, August 10, 2017 12:04 PM
  • User-1132163444 posted

    Hi, 

    just to help anyone just incase they bumped to this same problem, i was able to solved this by casting the PropertyInfo.GetValue result to IEnumerable

    var list = (IEnumerable)info.GetValue(obj, null);
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, August 11, 2017 3:02 AM