Where to add code to set default values for new entities

Posts   
 
    
ww
User
Posts: 83
Joined: 01-Oct-2004
# Posted on: 21-Jul-2016 02:52:09   

I'm using the LLBLGEN framework, migrating from version 4.1 to 5.0.

When a new entity is created, I need to set default values for many of the fields. In the past I did this by modifying the standard templates to add a call to an initialization routine that gets called in all constructors except the one that takes an IEntityFields2 and the one that takes a SerializationInfo.

I'd like to avoid modifying the templates, but I'm not sure where to hook in for this. Is there a method I can override to set defaults only when the entity isn't being fetched or deserialized?

daelmo avatar
daelmo
Support Team
Posts: 8245
Joined: 28-Nov-2005
# Posted on: 21-Jul-2016 07:12:41   

You could override OnInitialized on a partial class. Example:

public partial class CustomerEntity 
{
    protected override void OnInitialized()
    {
        this.City = "XYZ";
    }
}

Tests:

// new
var customer = new CustomerEntity();
Assert.AreEqual("XYZ", customer.City);

// fetched
customer = new CustomerEntity("ALFKI");
using (var adatper = new DataAccessAdapter())
{
    adatper.FetchEntity(customer);

}

Assert.IsFalse(customer.IsNew);
Assert.AreNotEqual("XYZ", customer.City);

For more info see Tapping into actions on entities and collections.

David Elizondo | LLBLGen Support Team
ww
User
Posts: 83
Joined: 01-Oct-2004
# Posted on: 21-Jul-2016 14:50:01   

I failed to mention I'm using the Adapter scenario.

From looking at the code I was thinking that OnInitialized gets called after field values have been set from the database. Isn't that what the fields parameter to InitClassEmpty is doing? So setting defaults in OnInitialized would override the db values.

The solution I ended up with is a Custom_EntityInitializationTemplate that calls a method to set default values only when the fields parameter is null.

Walaa avatar
Walaa
Support Team
Posts: 14946
Joined: 21-Aug-2005
# Posted on: 21-Jul-2016 19:08:25   

Well you have OnInitializing and OnInitialized which are called at the start / end resp. of InitClassEmpty.

And even in OnInitialized, you can test whether the entity is new and this.Fields.State == EntityState.New before setting fields to values.

ww
User
Posts: 83
Joined: 01-Oct-2004
# Posted on: 21-Jul-2016 21:25:01   

Thanks. I'll take a look at OnInitializing and also Fields.State.