Search code examples
linq-to-sql

LINQ to SQl Class generated by VS2008


You can refer to this post.

I am getting these Extensibility methods from VS2008 in my Linq to sql Entity.

What are these auto generated extensibility methods good for?

#region Extensibility Method Definitions
    partial void OnCreated();
    partial void InsertPerson(Person instance);
    partial void UpdatePerson(Person instance);
    partial void DeletePerson(Person instance);
    #endregion

#region Extensibility Method Definitions
    partial void OnLoaded();
    partial void OnValidate(System.Data.Linq.ChangeAction action);
    partial void OnCreated();
    partial void OnIDChanging(int value);
    partial void OnIDChanged();
    partial void OnIDRoleChanging(System.Nullable<int> value);
    partial void OnIDRoleChanged();
    partial void OnLastNameChanging(string value);
    partial void OnLastNameChanged();
    partial void OnFirstNameChanging(string value);
    partial void OnFirstNameChanged();
    #endregion 

And these events?

public event PropertyChangingEventHandler PropertyChanging;

public event PropertyChangedEventHandler PropertyChanged;

Solution

  • They are there so you easily can add behaviour to the different stages of a linq-to-sql entity.

    For example the OnValidate method is incredibly useful if you want to hook in custom validation for certain properties of a class. Say for example you do not want FirstNames that contains the letter A to be allowed. You could simply add a partial version of the OnValidate method that sets the object as invalid like so:

     partial void OnValidate(System.Data.Linq.ChangeAction action) {
        if(FirstName.Contains('a') {
           //Do some custom code that prevents saving to the database and notifies the user.
        }
     }
    

    In addition to explain the two events. They are there so you can add custom logic whenever a property is changing or has changed. For example you might wanna log to database everytime a user changes his FirstName (for what reason I know not) then you could hook into the PropertyChanging event and add behaviour for that.

    Something like this might explain it better:

     this.PropertyChanging += new PropertyChangingEventHandler(User_PropertyChanging);
    

    and then a method to handle the event:

    void User_PropertyChanging(object sender, PropertyChangingEventArgs e)
        {
            //Add some code to log the change to database...
        }