Best way to set initial default values for new entities?

Posts   
 
    
rbrown
User
Posts: 36
Joined: 11-Jun-2008
# Posted on: 17-Dec-2008 22:27:30   

I'm sure I'm just missing something, but I can't seem to find a clean way to default a specific boolean field to True when creating a new entity. Is there a method I should override in the custom (non-generated) partial class to accomplish this? Can someone point me in the right direction? Thanks!

LLBLGen v2.6, Adapter templates, SQL 2005, .NET 3.5

daelmo avatar
daelmo
Support Team
Posts: 8245
Joined: 28-Nov-2005
# Posted on: 18-Dec-2008 04:31:45   

You have a lot of ways to extend the generated code. In this case you could override the OnInitalized entity method in a partial class (or CODE_REGION):

public partial class YourEntity
{
        protected override void OnInitialized()
        {
            base.OnInitialized();
            
            // your code here...
        }
}
David Elizondo | LLBLGen Support Team
rbrown
User
Posts: 36
Joined: 11-Jun-2008
# Posted on: 18-Dec-2008 15:29:15   

I tried that. It did indeed set the values, but it overrides the fetched values as well (for existing entities). I even tried checking for IsNew but that always appears to be true at the time of OnInitalized, so it seems not to have an effect.

//THIS IS NOT RIGHT
    partial class ExecDeviceRouteEntity
    {
        protected override void OnInitialized()
        {
            base.OnInitialized();

            if (IsNew) // always appears to be true in my testing
            {
                Priority = 1;
                AllowPolling = true;
            }
        }
    }

This results in Priority=1 and AllowPolling=true, even if the persisted values in the DB are different (not good!)

After trying that, I had a better idea of what to search for, and finally I found a post (http://www.llblgen.com/tinyforum/Messages.aspx?ThreadID=14456&StartAtMessage=0&#80655), in which Frans suggests this:

       protected override void OnInitialized()
        {
            base.OnInitialized();
            if((this.Fields!=null) && (this.Fields.State!=EntityState.Fetched))
            {
                //SET DEFAULTS HERE
                Priority = 1;
                AllowPolling = true;
            }
        }

This appears to be accomplishing what I need. Thanks for your response, and pointing me in the right direction.