问题
I'm creating an object in this way:
var assembly = typeof (Cliente).Assembly;
var Tipo = assembly.GetType("Datos." + tipoItem);
var item = Activator.CreateInstance(Tipo);
where tipoItem is the name of a class and Datos is the respective namespace.
Cliente is a class in the same namespace.
To store the object in the database I have this generic method:
public void AddItem<TItem>(TItem item) where TItem : class
{
db.Set<TItem>().Add(item);
db.SaveChanges();
}
When debugging, the type of the item object is right. If tipoItem is "EmailCliente" then the type of item is Datos.EmailCliente.
The AddItem method receives item as a Datos.EmailCliente object but an exception is thrown:
"The entity type Object is not part of the model for the current context"
When debugging, TItem is of type object instead of Datos.EmailCliente and that's the problem.
I did try to cast item to Tipo using (Tipo), as Tipo, Convert.ChangeType(item, Tipo) but none of those work.
How can I cast item so the AddItem method accepts it.
TIA
EDIT:
Based on Andrei's answer this is the code that's working.
MethodInfo method = typeof(ControlDatos).GetMethod("AddItem");
MethodInfo generic = method.MakeGenericMethod(new[] { Tipo });
generic.Invoke(cd, new object[] { item });
where cd is an instance of the class ControlDatos where the AddItem method is defined.
回答1:
When you are calling AddItem(item)
, compiler is deriving generic type from the argument and substituting it into method call. Since item
is of type object (at compile time!) - this is what compiler is using. So really you are calling AddItem<object>(item)
, which gives you the error.
To resolve this you have to make a call of AddItem
via reflection:
MethodInfo method = typeof(ItemRepository).GetMethod("AddItem", BindingFlags.Public | BindingFlags.Static);
MethodInfo generic = method.MakeGenericMethod("Datos." + tipoItem);
generic.Invoke(null, new object[]{item});
where ItemRepository
is the class which defines AddItem
method.
来源:https://stackoverflow.com/questions/17381897/the-entity-type-object-is-not-part-of-the-model-for-the-current-context