vendredi 21 août 2015

Extracting a list property of type

I have an object that contains many lists of other objects. I will provide a simple example.

public class BaseApplicationData
{
    public long Id { get; set; }
}
public class Phone : BaseApplicationData
{
    public string PhoneType { get; set; }
    public string Number { get; set; }
    public string Extension { get; set; }
}
public class Employer : BaseApplicationData
{
    public double Salary { get; set; }
    public string Name { get; set; }
    public string EmployementType { get; set; }
}
public class Applicant : BaseApplicationData
{
    public string Name { get; set; }
    public string EmailAddress { get; set; }
    public List<Phone> PhoneNumbers { get; set; }
    public List<Employer> Employers { get; set; }
}

In the actual code I'm working with, there are a lot more of these lists. During the processing, we need to be able to perform CRUD actions for each of these lists. The process is the same for each list. So, rather than write a set of CRUD methods for each list type, it occurred to me that I could use generics and / or reflection to accomplish these actions for each list.

So I created a method that does this but my results are not what I was expecting. Using the example objects above, I created an applicant object and added an Employer object to it. (This was to simulate a list with data already in it.) I then called my method (shown below).

public long CreatePropertyValue<T>(Applicant applicant, T data, string propertyName)
{
    long newId = 0;
    var listproperty = applicant.GetType().GetProperty(propertyName);
    // Here is the problem, even with data in the list, listData.Count is always 0.
    List<T> listData = listproperty.GetValue(applicant, null) as List<T>;
    // psuedo code
    if list is null, create a new list
    assign a new Id value to object data (parameter)
    Add the data item to the list
    update the property of the applicant object with the updated list
    return newId;
}

A call to the method would look something like this. test.CreatePropertyValue(applicant, emp, "Employers");

When I call this method with no data in a list, I get null on the value as expected. When I call this with data in the list already, the value of listData is a list of the correct type but with zero items in the list. Looking at listproperty.PropertyType.GetGenericArguments() I can see the actual items in the list. I want to be able to get the collection of listData based on the propertyName and type T then be able to add my T data item to the list and save it back. Similarly, I'll need to be able to update, delete, and return the list as well.

I've looked at several questions on the site but none of them explain to me why my list contains 0 items when I use getvalue on the property.

I would appreciate any help you can provide.

Thanks





Aucun commentaire:

Enregistrer un commentaire