Entity Framework Code First callback on object ins

2019-05-18 06:14发布

问题:

This may be a far fetched question, but is it possible to have a callback fire in an entity object, whenever a new instance of it has been loaded from the database (as part of e.g. a linq query), a call to Create or similar?

The purpose of such a callback would be to convey a context, or set of initialization parameters, from the enclosing business object.

回答1:

DbContext definitely doesn't have it but you can try to convert it back to ObjectContext and use:

var objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;
objectContext.ObjectMaterialized += ...

It will fire after loading object from database (I'm not sure if it fairs for newly created objects as well). It is global event for all objects so you will have to put some logic into handler to run your code only for some types.