I have a generic method in my repository which updates a property common to all the objects in my edmx model:
private void SetUpdateParams(TEntity entity)
{
PropertyInfo prop = typeof(TEntity).GetProperty("CommonProperty");
prop.SetValue(entity, "Some Value", null);
}
This property is called by the add, update and delete methods. Example:
public void Delete(TEntity entity)
{
SetUpdateParams(entity);
_objectSet.DeleteObject(entity);
txDB.SaveChanges();
}
This all works fabulously well, until I try to include children in a cascade delete scenario. Since the sprocs I have to use require that this certain property is set, I must now recurse through the relationships and set this property on any loaded children in the ObjectSet. Problem is I can’t seem to figure out any way to do that. Has anyone done something like this before?
It’s not the easiest solution and can be a tad tedious, but I implemented what you’re needing in a project of mine by spanning the object graph, updating the property as I found it, and keeping track of what I’ve visited. It gave great flashbacks to undergrad computer science classes. =)
Essentially, take your object, get its properties, and push them on a stack. For each property on the stack, test if it’s the property you’re looking for. Handle if match, ignore if simple data type, add to stack if complex object.
A couple of things that aided me in my implementation:
ObjectContext) custom Save() method. I call this fixup and then callbase.SaveChanges().Like I said, not an easy, straightforward question, but my code handles deep object graphs and updates multiple property instances. If interested, I can follow-up with some pseudo code.
EDIT/UPDATE
As the code shows, I’m interested in updating current UserName and DateTime values for any number of objects that may appear in the graph.
Notes:
IInsertedInfocontains the properties that we need to update. So if an object implementsIInsertedInfo, we know to update its properties.IRequiresCurrentUserDateTimeis one that has, somewhere in its graph, an object that implementsIInsertedInfo.ObjectStateManagerfor objects that need to be saved/updated.I don’t claim this to be the most succinct solution, but it works fine for me. Additionally, checks for
IRequiresCurrentUserDateTimeand other filters (some omitted for clarity’s sake) are used solely to keep the search space manageable and to avoid spanning .NET objects, non-class types, etc.