5

I have an instance of a class called AccessData, which inherits from DbContext. So it is an Entity Framework code first context class 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 have identified one of these DbSet properties on the AccessData object like this...

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

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

Given that I only have a FieldInfo object that represents the DbSet field, how do I call the Add method of this particular Field on the AccessData object and pass in an object?

Or in other words how do I call the following?

accessData.<FieldInfoType>.Add(obj);

Hope this makes sense.

jdavis
  • 8,255
  • 14
  • 54
  • 62

1 Answers1

8

Get the field's value:

object fldVal = listField.GetValue(accessData);

Get the MethodInfo for the method you want to invoke:

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

And invoke it:

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

Or if you're using .NET 4, you may be able to use the new dynamic keyword to simplify the last 2 steps:

dynamic fldVal = listField.GetValue(accessData);
fldVal.Add(obj);
M.Babcock
  • 18,753
  • 6
  • 54
  • 84
  • So this works because GetValue returns a reference to the object that the fieldInfo is referring to? I has assumed from the name that GetValue just returned a value rather than the object itself or something. – Matthew Lock Mar 17 '15 at 03:12
  • @MatthewLock - I'm not quite sure I understand what _value_ you expect to get. `GetValue()` will return whatever would normally be returned by dereferencing the field (e.g. `fldVal = obj.ListField;`) – M.Babcock Mar 17 '15 at 11:29
  • What I don't understand is why you can call GetType() on the returned value object and be able to get a methodInfo on the object that returned the value, and then reach the instance of the object using Invoke. It's great that it works like that, but it seems odd. – Matthew Lock Mar 17 '15 at 22:55