Search code examples
c#entity-framework-6

IEnumerable to Object?


I'm a little confused on how exactly this works. I have an IEnumerable<T> list that I'm pulling from a stored procedure in a mySQL database.

IEnumerable<CheckInVar> CheckInVars = 
    context.Database
           .SqlQuery<CheckInVar>("Call getCheckinVars(\"WEB\")").ToList();

Now, do I need to loop through this object to pull out the properties so that I can use them such as this?

foreach (var prop in CheckInVars.GetType().GetProperties())
{
    Console.WriteLine("{0} = {1}", prop.Name, prop.GetValue(CheckInVars, null));
}

Or can I directly work off of that IEnumerable<CheckInVar> object, or do I need to convert that to work with it?

public class CheckInVar
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    [Column("ID")]
    public int ID { get; set; }
    public string Code { get; set; }
    public string VarValue { get; set; }
    public string AccessMethod { get; set; }
    public string Active { get; set; }
    public string DateCreated { get; set; }
    public string DateUpdated { get; set; }
    public string UpdatedBy { get; set; }
}

Solution

  • Yes.

    If you, for some reason, wish to access each collection (IEnumerable) item's properties via reflection, then you will have to loop through the IEnumerable and process each item in turn.

    Using your example:

    foreach(var checkInVar in CheckInVars)
    {
        foreach(var prop in checkInVar.GetType().GetProperties())
        { 
            Console.WriteLine("{0} = {1}", prop.Name, prop.GetValue(checkInVar)); 
        }
    }
    

    As others have mentioned though, is reflection really necessary? Can you not access the properties directly?

    I'm guessing you may be using reflection to allow changes to the CheckInVar type without having to change your processing code.