Search code examples
linq-to-sqlinheritanceabstract-classimplementationpartial-classes

Partial Method Inside Abstract Class (C#)


I'm creating an abstract class that can be inherited in a partial class of a LINQ to SQL class. The LINQ to SQL class contains a bunch of built-in partial methods. Is there a way that I can implement one or more of the partial methods in the abstract class? I know that partial methods can only be contained within partial classes or structs. I'm sure there's got to be another way to do it.

Here's more detail:

  • I may have a database table called News. If I create a LINQ to SQL dbml file containing this table, the auto-generated code generates a partial class for News.
  • This partial class contains several partial methods.
  • I have a class that I'm building that contains several methods that I'd like to use across all my LINQ to SQL classes.
  • One of these methods is a partial method added to each LINQ to SQL class. I have a common body to use for this method. Rather than adding this method to each partial class, I'm looking for a way to create it once and inherit it with my base class inheritance.

Hope that helps explain more.


Solution

  • Partial methods are not usable over inheritance. You could add regular methods to the abstract base class, but they won't automatically "pair" with the partial method declarations. So: no. You can, of course, simply have the partial method implementation call into the base-class.

    Note also that if the common code relates to things like audit (who/when), you can also do this by overriding the DataContext's SubmitChanges method, and calling GetChangeSet:

        public override void SubmitChanges(ConflictMode failureMode)
        {
            ChangeSet delta = GetChangeSet();
            //... use delta.Updates, delta.Inserts and delta.Deletes
            base.SubmitChanges(failureMode);
        }
    

    Finally, note that you can also specify a common base-class for all your entities in the dbml (like so); you don't have to do it by hand in each partial class.