Is there an automatic way to add base classes to Linq2Sql entities?
I know I can define a partial and implement that but there has to be an automated way, right?
Is there an automatic way to add base classes to Linq2Sql entities?
I know I can define a partial and implement that but there has to be an automated way, right?
EDIT: Marc's answer is clearly the right way to go in this case, but I'm leaving this answer here for posterity - it's a handy trick to know about in some cases, where you only need a partial class to change the inheritance/interfaces of a class.
I don't know of any automated way, but if you wanted to do this for multiple classes and only wanted to specify the base class, you might consider creating a file just for the partial class declarations. I use this approach in Protocol Buffers to make the internal representation classes which are autogenerated implement a particular interface.
See PartialClasses.cs for this example as code. (Ignore the TODO - it's fixed locally, but I haven't pushed for a little while :)
Some people have written their own code templates in place of the DBML approach. Going that route you can easily add the base classes yourself.
LINQ to SQL template for Visual Studio 2008 is a good starting point
The LINQ-to-SQL code-generator supports this directly.
The base-class for the data-context can be set in the designer, as the Base Class
property. Alternatively, edit the dbml directly: right click, "Edit With...", "XML Editor"
To change the base class for the entities, set the type:
<Database EntityBase="Some.NameSpace.Foo" ... >
To change the base class for the data-context, set the type:
<Database BaseType="Some.NameSpace.Bar" ... >
In both cases, use the fully-qualified type in the attribute. Et voila.
Note that because it is very literal, you can also use this approach to make your entities implement an interface - for example, when my classes have properties like LastUpdated
and UpdatedBy
, I might have an IAuditable
interface that defines these. Then I can put code in my data-context's SubmitChanges
(override) that calls GetChangeSet()
and sets these values for all the IAuditable
entities being updated; very sweet.