none
Entity Framework 5: How to be Notified when an Object has been Materialized? RRS feed

  • Question

  • There are several times where I've needed to change (or set another non-EF property) when the underlying object is materialized. (In earlier versions of EF it was easy to do but I can't figure out how to do it in EF5.) How do I do this in EF5?

    For example, I have a DateTime2 SQL column and I need to set the corresponding .NET DataTime property from Unspecified to UTC.

    Saturday, July 6, 2013 9:52 PM

Answers

  • Hi, you can get to the ObjectContext from the DbContext as shown below. Then you can listen for the ObjectMaterialized event as you did in EF 4.x.

    public class MyContext : DbContext
    {
    	private ObjectContext oc;
    
    	public MyContext() : base("myConn")
    	{            
    		oc = (this as IObjectContextAdapter).ObjectContext;
    
    		oc.ObjectMaterialized += new ObjectMaterializedEventHandler(oc_ObjectMaterialized);
    
    	}
    
    	private void oc_ObjectMaterialized(object sender, ObjectMaterializedEventArgs e)
    	{
    		//do stuff		
    	}	
    }

    Sunday, July 7, 2013 2:15 PM