Michał Turecki
Michał Turecki

Reputation: 3167

How to initialize object in Entity Framework using POCO and DbContext after loading?

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?

Upvotes: 2

Views: 4473

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364269

You can use an ObjectMaterialized event exposed on ObjectContext:

var settings = new Settings();
settings.PrintName = false;

var dbContext = new MyDbContext();
var objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;
objectContext.ObjectMaterialized += (sender, e) => {
    var user = e.Entity as User;
    if (e != null) {
       // Now you can call your initialization logic
       user.Settings = settings;
    }
};

var john = dbContext.Users.Where(x => x.Name == "John").FirstOrDefault();
Assert.AreEqual(john.Settings, settings);

ObjectMaterialized event should be raised after populating common (scalar and complex) properties from database record but before population navigation properties.

Upvotes: 5

Related Questions