Using reflection, call the field method on an object that already exists

I have an instance of the AccessData class that inherits from DbContext. So this is the first class of Entity Framework context code and looks like this ...

public class AccessData : DbContext
{
    public DbSet<apps_Apps> apps_AppsList;
    public DbSet<apps_AppsOld> apps_AppsOldList;
    ...
    //Several other DbSet<> properties
}

Using Reflections, I identified one of these DbSet properties on an AccessData object, like this ...

var listField = accessData.GetType().GetField(typeName + "List");

Now I need to be able to add objects to this DbSet property.

Given that I have a FieldInfo object that represents the DbSet field, how can I call the Add method of this field in the AccessData object and pass the object?

Or, in other words, how do I invoke the following?

accessData.<FieldInfoType>.Add(obj);

Hope this makes sense.

+5
source share
1 answer

Get field value:

object fldVal = listField.GetValue(accessData);

MethodInfo , :

MethodInfo addMethod = fldVal.GetType().GetMethod("Add", new Type[] { typeof(obj) });

:

addMethod.Invoke(fldVal, new object[] { obj });

, .NET 4, dynamic :

dynamic fldVal = listField.GetValue(accessData);
fldVal.Add(obj);
+8

All Articles