Monday, January 25, 2010

LINQ to SQL - Customising Insert, Update, and Delete Operations

The DataContext "Extensibility Method Definitions" can be used to modify the default behaviour of the Insert Update Delete partial classes:

namespace LinqToSql.OverrideDatabaseStatements
{
public partial class NorthwindDataContext
{
partial void InsertCustomer(Customer instance)
{
string result = "I'm here InsertCustomer";
this.ExecuteDynamicInsert(instance);
}
partial void UpdateCustomer(Customer instance)
{
string result = "I'm here UpdateCustomer";
this.ExecuteDynamicUpdate(instance);
}
partial void DeleteCustomer(Customer instance)
{
string result = "I'm here DeleteCustomer";
this.ExecuteDynamicDelete(instance);
}
}
}

This has proved useful to automatically-populate audit details e.g. DateAdded, AddedBy etc.

Thanks to Pedro Rainho's post for this!

No comments: