tags:

views:

216

answers:

1

How come the "Table" classes Generated in the Dbml do not contain useful events like

OnBeforeInsert OnBeforeUpdate

OnAfterInsert etc.

Am I missing something?

This question is related to frustration trying to set timestamp columns.

UPDATE

I created the following method of doing this neatly what does everyone think?

public class Model
{
    internal virtual void OnBeforeInsert()
    {
    }
    internal virtual void OnBeforeUpdate()
    {
    }
}

public partial class DbDataContext
{
    public override void SubmitChanges(System.Data.Linq.ConflictMode failureMode)
    {
        foreach (var insert in this.GetChangeSet().Inserts)
        {
            if (insert is Model)
            {
                ((Model)insert).OnBeforeInsert();
            }
        }

        foreach (var update in this.GetChangeSet().Updates)
        {
            if (update is Model)
            {
                ((Model)update).OnBeforeUpdate();
            }
        }

        base.SubmitChanges(failureMode);
    }
}

public partial class Address : Model
{
    internal override void OnBeforeInsert()
    {
        var created = DateTime.Now;
        this._Modified = created;
        this._Created = created;
    }
}
+3  A: 

I had a similar issue like this recently.

There is a partial method in the generated class for "OnValidate". Simply declaring the method in your partial will force it to be called (vb.net does not support partial methods like c#) or in c# simply declare a partial method.

The method is passed a System.Data.Linq.ChangeAction enum that is either: Delete, Insert, Update, or None.

Below is a sample of what you did using the built in partial method.

public partial class Address
{

    private partial void OnValidate(System.Data.Linq.ChangeAction action)
    {
       if (action == System.Data.Linq.ChangeAction.Insert)
       {
           var created = DateTime.Now;
           this._Modified = created;
           this._Created = created;
       } else if (action == System.Data.Linq.ChangeAction.Update) {
           this._Modified = DateTime.Now;
       }
    }

}
Tom Anderson