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.
Get the field's value:
Get the
MethodInfo
for the method you want to invoke:And invoke it:
Or if you're using .NET 4, you may be able to use the new
dynamic
keyword to simplify the last 2 steps: