Inheritance in Linq RRS feed

  • Question

  • Hi,

    I'm using Linq-to-Sql in my project and I have few columns common in all of my tables. For example to keep track of who inserted or updated a row and when, I have the following columns in every tables

    Now I want to have a base class, say RowInfo, with these properties and want to inherit all Linq-generate entities from this RowInfo, rather than repeatedly having the same attributes in all entities. But to use Base class in linq I need to have a discriminator attribute in my entity which I don't to use, because then in all tables I need to maintain an extra filed. Also the primary key  is not in the base class  RowInfo, rather in the derived class.  The primary key is, for example  for table Employee, primary key is EmployeeID, for table Order primary key is OrderID.

    So I can't use normal inheritance as I don't have primary key defied in the base class. Also I don't want to add discriminator column in every entity. So is there any way I can use inheritance?

    Sohel Rana
    Saturday, February 7, 2009 5:39 AM


  • LINQ to SQL's own inheritance support requires that all types in a hierarchy that require mapping be mapped to a single table.

    However you can achieve this is a slightly different by using the inheritance features of C# or VB.NET. Create your base class (RowInfo) with these four properties (CreatedBy, UpdatedBy, CreatedDate, Updated) and ensure they are virtual.

    Then make the entity class such as Order inherit from your base class in the partial code, e.g. public Order : RowInfo { ... } and finally you must then override each of the virtual properties you wish to map and add the [Column] attribute. To ensure you use the base class logic leave the properties setters and getters passing to base. e.g.

    public Order : RowInfo
    public override CreatedBy { get { return base.CreatedBy; } set { base.CreatedBy = value; } }

    Friday, March 6, 2009 11:01 PM