Skip to content

David Turvey's Blog

All About Development

Archive

Tag: DBML

If you need your all your LINQ to SQL entities to inherit from a base class or to implement an interface there is an easy way to do it. The first way that comes to mind for most people is to create a partial class for the entities and specify the inheritance (or interface implementation) in the partial class. While this will work it is a mission as it means you need a matching partial class for every LINQ to SQL entity in your DBML, and there is no guarantee that any new entities that are added by other team members will inherit from the base class or implement the interface.

There is a far simpler way to ensure that all LINQ to SQL entities inherit from a base class or implement an interface. Unfortunately there isn’t a way to do it from the LINQ to SQL designer, you need to open up the DBML file in a text editor. On the Database node simply add the attribute EntityBase along with the name of the base class or interface.

<Database Name="Northwind"
	Class="MyDataContext"
	xmlns="http://schemas.microsoft.com/linqtosql/dbml/2007"
	EntityBase="MyEntityBase">
</Database>

If the base class or interface is not in the same namespace as your LINQ to SQL entities then you will need to specify the full qualified name of the base class or interface.

Normally when you commit a change to the database using LINQ it will generate SQL to perform the insert/update/delete action. Most of the time this is fine, but LINQ does provide the ability to override this behaviour and specify a stored procedure that should be executed instead of the default behaviour. And luckily it’s really easy.

First, create your stored procedure, normally if you are creating an insert or update stored procedure the proc will have a parameter for each field but this is not a requirement as you can map the individual fields to the properties of the class.

Drag the stored procedure onto your DBML so that the LINQ framework creates a method for the stored procedure, in this example the stored procedure is called InsertLessee.

LINQInsert1

Then right click on the LINQ entity in the DBML and select Configure Behaviour.

LINQInsert2

Then (1) choose the behaviour to replace, (2) select Customize and select the stored procedure from the drop down list, in this case InsertLessee, and (3) if needed alter the stored procedure parameter to class property mapping.

LINQInsert3

It is as simple as that, now whenever a Lessee is inserted the LINQ framework will call the stored procedure instead of generating SQL at runtime.