Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Code First callback on object instantiation

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.

like image 214
ShawnL Avatar asked Apr 18 '26 00:04

ShawnL


1 Answers

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.

like image 158
Ladislav Mrnka Avatar answered Apr 19 '26 13:04

Ladislav Mrnka