views:

25

answers:

1

I would like to know when entities in a certain database table are either created or updated. The application is essentially a CMS, and I need to know when changes are made to the content so that I can reindex them for searches.

I know that the autogenerated LINQ to EF class has overridable methods for when certain fields change, but I need to know when the whole object is created/updated, not just a single field. I tried putting it in OnCreated, only to find that meant OnObjectInitialized and not OnObjectInsertedIntoDBTable xD

I did some searching and came across this link. The "Entity State" section looks like its what I want, but I'm not sure how to use this information. Where do I override those methods?

Or perhaps there is a another/better way?

(I also need to know this for another part of the system, which will send notifications when certain content is changed. I would prefer this code to execute automatically when the insert/update occurs instead of placing it in a controller and hoping hoping I always call that method.)

+1  A: 

You need to get ObjectStateEntry(s) from the ObjectStateManager property of the ObjectContect.

var objectStateEntries = this.ObjectStateManager.GetObjectStateEntries(); 

This entries contain every object state you've pulled down per context and what kind of actions where performed on them.

If you are using EF4 you can override the SaveChanges method to include this functionality. I've used this technique to audit every change that occurs in the database instead of triggers.

jfar
I'm still lost :-/ I don't completely understand EF to be honest, and I'm using ASP.NET MVC 2 (.NET 4) so I believe all of that is generated for me in via the .dbml designer (creates a class which inherits System.Data.Linq.DataContext). Am I confusing EF with something else or maybe just looking in the wrong places?
Colin O'Dell
@Colin O'Dell - There are 4 different generation strategies so its never guaranteed any of the generated code will have these hooks. Basically every ORM has some concept of state tracking within it. An object gets brought down and a reference ( sorta ) is kept around. EF's ObjectContext provides this state tracking. This is what you need to track when entities are created and updated.
jfar
OK thanks. I've know that I can pull an entity from the data context, modify it, and call Save() on the data context, which knows exactly what has been changed. I'll dig a little deeper and see what I can find. Thanks again for the help!
Colin O'Dell