Tuesday, March 4, 2008

Superclass your entities without using SQLMetal

Superclass your entities without using SQLMetal

Often I look through posts and find that people are repeating a lot of code in partial classes, when some of this work could be done in a parent class. The only documented way to do this seems to be the SQLMetal.exe command line tool. However, it's entirely possible to do this without SQLMetal.exe. To make this possible, it's just a simple matter of using notepad to edit your existing dbml file and adding the following to the "Database" element:

EntityBase="[EntityBase]"

Where [EntityBase] can be replaced with the name of your superclass.

Next, save the file and go back to your project. Right click on the DBML file in the VS project and select "Run custom tool"... the next thing you know all your LINQ to SQL objects will be subclasses to what you specified.

You can update this anytime, without screwing anything up... and the way it does it is pretty lazy...There's no checking of any sort, so you can prefix your class with a namespace, add multiple interfaces or just have your entities implement an interface without a base class.

E.g.

EntityBase="Sample.EntityBase"
EntityBase="Sample.EntityBase, IMyInterface1, IMyInterface2"
EntityBase="IMyInterface"

Anyway, I've already used this for a number of reasons - quite useful.

Cheers

Matt.

No comments: