Using EntityFrameworkCore to connect to a database, After creating models of all tables and a DbContext, I create a new object of this Context with name myContext which has a property (with name of listName) of type List. I want to create a new object and add it to the list. Everything works fine but the last line of code:
myList.GetType().GetMethod("Add").Invoke(myList, new[] {myObj});
which throw an exception of type System.Reflection.TargetInvocationException
here is the whole code:
private void AddNewObjectToThisList(string listName) {
var myList = myContext.GetType().GetProperty(listName).GetValue(myContext);
var objType = myList.GetType().GetGeneric Arguments().Single();
var myObj = Activator.CreateInstance(objType);
myList.GetType().GetMethod("Add").Invoke(myList, new[] {myObj});
}
Aucun commentaire:
Enregistrer un commentaire