简体   繁体   中英

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 eg 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM