Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set properties on a generic entity?

I'd like to check if an entity has 3 properties. CreatedDate, ModifiedDate, and ModifiedBy.

Right now I am just hardcoding the ones that I know have them in the SaveChanges() method of my Object Context.

For instance:

bool newEntity = (entry.State == EntityState.Added);

if (type == typeof(Foo))
{
  var r = entry.Entity as Foo;
  if (r != null)
  {
    if (newEntity) 
      r.CreatedDate = DateTime.Now;
    r.ModifiedDate = DateTime.Now;
    r.ModifiedBy = HttpContext.Current.User.Identity.Name;
  }
}

I know it's possible to check if an object has a certain method using code similar to this:

public static bool HasMethod(this object objectToCheck, string methodName)
{
    var type = objectToCheck.GetType();
    return type.GetMethod(methodName) != null;
} 

But how would I get at those properties without directly casting the entity?

How can I do something like:

if (HasMethod(entry.Entity))
      entry.Entity.ModifiedDate = DateTime.Now;

I am using ASP.Net MVC 4.

like image 880
Smith Avatar asked Jun 06 '13 12:06

Smith


1 Answers

You can use below method. It will set the property if it exists. Using GetType at each call may cause some overhead, it needs optimization.

private bool TrySetProperty(object obj, string property, object value) {
  var prop = obj.GetType().GetProperty(property, BindingFlags.Public | BindingFlags.Instance);
  if(prop != null && prop.CanWrite) {
    prop.SetValue(obj, value, null);
    return true;
  }
  return false;
}

Usage

TrySetProperty(entry.Entity, "ModifiedDate", DateTime.Now);
like image 118
Mehmet Ataş Avatar answered Oct 02 '22 20:10

Mehmet Ataş