I’m using EF5. I would like to to initialize every object of DbSet collection contained in DbContext, preferably (but not necessarily) after object fields (but not necessarily relations with other POCO) has been initialized. This might be shortened as “post-construction interception” or “post-load interception”.
Initialization needs to set some properties of objects with an instance of an object that lives in parallel with DbContext instance (current user settings etc).
So basically:
var settings = new Settings();
settings.PrintName = false;
var context = new MyDbContext();
// here initialize context so that every User object get initialized with settings
var john = context.Users.Where(x => x.Name == "John").FirstOrDefault();
Assert.AreEqual(john.Settings, settings);
What is the possible approach to achieve this, other than looping through all objects in collection and manually setting properties?
You can use an
ObjectMaterializedevent exposed onObjectContext:ObjectMaterializedevent should be raised after populating common (scalar and complex) properties from database record but before population navigation properties.