I would like to create a generic update method in a ObjectContext, using a generic class. I need to loop all properties and update them based in a generic entity that i pass to my generic update method. The update method:
public void Update(T entity)
{
if (entity == null)
{
throw new ArgumentNullException("entity");
}
var propertiesFromNewEntity = entity.GetType().GetProperties();
// I've a method that return a entity by Id, and all my entities inherits from
// a AbstractEntity that have a property Id.
var currentEntity = this.SelectById(entity.Id).FirstOrDefault();
if (currentEntity == null)
{
throw new ObjectNotFoundException("The entity was not found. Verify if the Id was passed properly.");
}
var propertiesFromCurrentEntity = currentEntity.GetType().GetProperties();
for (int i = 0; i < propertiesFromCurrentEntity.Length; i++)
{
propertiesFromCurrentEntity.SetValue(propertiesFromNewEntity.GetValue(i), i);
}
}
But this doesn’t work because the properties are passed by value, Right? So, there is a way to modify the current entity properties?
OBS: After Update, Insert and Remove methods my framework calls myContext.SaveChanges().
Assuming you want to set values from
entitytocurrentEntity(otherwise, just use the reverse).