Multi-layer LINQ via Extension Points

As promised a few days ago, I will be covering multi-layered architecture as it relates to LINQ.

The first thing we need to evaluate is how microsoft intended multi-layered architecture to work.  I mean, if we want to know how to do this, the best place to start is with the people who created the technology in the first place, right?

So, remember when we discussed partial functions?  Partial functions are the key to understanding the multi-layer capabilities of LINQ.

The LINQ to SQL classes are composed of the DataContext class and the class that represents a row in each table.  We’ll call that the Table class for now.  Each of these classes have a set of partial functions.  The DataContext class has the following partial functions:

  • partial void OnCreated();
  • partial void InsertTable(Table instance);
  • partial void UpdateTable(Table instance);
  • partial void DeleteTable(Table instance);

where Table represents a table class.  You would, therefore have an Insert, Update and Delete partial method for each table in your DataContext.

The table classes also have a set of partial methods defined for them.

  • partial void OnLoaded();
  • partial void OnValidate(System.Data.Linq.ChangeAction action);
  • partial void OnCreated();
  • partial void OnFieldChanging(typeName value);
    partial void OnFieldChanged();

So you can write code that will fire when the row is created, loaded, or validated as well as when the field is being set, or right after each field has been set.  Just to avoid any confusion, loaded gets called right after the row is filled from the database and validated is called right before it gets saved back.

So, here’s what you might be able to achieve with this.

  • Create special Insert, Update and Delete handlers for tables that need special handling.  For example, maybe you can’t implement cascading delete at the database level for whatever reason, you could handle it in code during the delete event.
  • Do data transformation on rows when they are loaded and transform back when the row is saved.
  • Validate data as you are changing the record.

Related Post

Comments are closed.