# Sunday, August 24, 2008
« Spectacle | Main | Nemerle Macros - Record »

There are currently two approaches when using L2S. Either adding attributes to classes to denote columns, or creating an external XML mapping definition. Neither of these is great. Attributes mix non domain concerns, namely database schema, into domain objects. XML mapping needs to be kept in sync with the classes it describes. During the early stages of a new project, the structure of classes can vary and morph over time. So manual mapping is annoying.

My suggestion is to create a "convention-based" mapping. Where you can define POCOs and then have reflection to build the mapping, based on some simple naming conventions. This mapping can then be used by a DataContext and a database created from it. (Note that I am only considering green field developments, where we are working "code-first".)

The conventions I have thought about so far include:

  • A property named "Id" will be the primary key.
  • If Id is an int then make it auto incrementing.
  • All primitive, string and DateTime properties are columns.
  • All properties having the type of another entity in the DataContext are associations.
  • All properties of type EntityRef<T> are associations.
  • There must be a foreign key Id property defined for associations.
  • Any property with subtype a of IList<T> is an association.

One-to-many associations need to be a bit smart with their names. Consider:

class Customer {
  public Employee ReferringEmployee { get; set; }
}
class Employee {
  public List<Customer> ReferredCustomers { get; set; }
}

The mapping needs to understand the "ing" and "ed" relation. Also, we'll perhaps need support for TechSupportEmployee <--> TechSupportedCustomers.

The conventions should follow the usual rules of English grammar. I hope, therefore, that they do not interfere with the universal language discovered by domain driven design.

As a project begins to settle down, there will be requirements that the convention mapping doesn't support. Rather than having to switch to full manual XML mapping, perhaps an augmentation layer could applied. This could describe specific cases of the mapping that are different. For example, a certain primary key column using GUIDs instead of integers.

c# | linq | linq-to-sql | orm
Sunday, August 24, 2008 11:09:43 AM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  |