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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With