Entity Framework Code First callback on object instantiation

冷暖自知 提交于 2019-12-22 11:13:00

问题


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.



来源:https://stackoverflow.com/questions/6690197/entity-framework-code-first-callback-on-object-instantiation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!