Linq To SQL Tutorial – EntityBase – Base class for entities

When using Linq To SQL you may often find yourself in a position where you want each of your entities to inherit from a base class.  As generated classes are partial classes you could create a second partial class for each entity which inherits a base class, but this is impractical.  The O/R designer does not give you the option for a base entity class but it can be achieved using the SQLMetal command line tool.

SQLMetal allows you to create a .dbml file or a code file containing your entities.  SQLMetal Builder provides a simple user interface for the command line tool and also generates batch files.

I have created an abstract class called EntityBase which I want all of my generated entities to inherit. I can use the following arguments with SQLMetal in order to create my entities that inherit this class.

<br />
SQLMetal.exe /server:localhost /database:University /code:University.cs /namespace:Entities /context:UniversityDataContext /entitybase:EntityBase /pluralize<br />

SQLMetal will look at server localhost and the database University.  It will create the entities in an file called University.cs with the namespace Entities.  The DataContext will be called UniversityDataContext and all entities will inherit EntityBase.  I am also using the pluralize argument which plurlises the table names, for example Student become Students;  I find this is more intuative when writing queries.

Posted on by Joe in C#, Linq

3 Responses to Linq To SQL Tutorial – EntityBase – Base class for entities

  1. flash-player

    Nice!

  2. Flash gordon

    As generated classes are partial classes you could create a second partial class for each entity which inherits a base class, but this is “inpractical”.
    ————————————————————
    Why it is impractical? I use this approach in my apps and it works fine. See Asp.net unleashed – stephen walther.

  3. Joe

    I’m sure I replied to this but the comment doesn’t seem to be here.

    Impractical is probably the wrong choice of word, but why create a partial class for every entity just to implement a base class when you can do it using this method.

Add a Comment