Custom Properties On A LINQ 2 SQL Model

When you create a LINQ 2 SQL model all your properties are auto generated for all the tables in your database that you drag onto the designer.
All good until you need  to put a few extra properties onto an entity class maybe for aggregating some data from another table.

I am currently working on an application that will eventually be deployed throughout Britain's National Health Service (scary business!).
I needed to have an aggregated count of all treatment’s a patient had been administered. I have two table’s patients and treatments and
there is a one to many relationship between them.

(Please note the data and schema below do not represent my real applications schema or data.)

LinqModel 
I wanted to have a property on the patient class to show the count off all treatments given to the patient by counting the patients treatments .
To do this I needed to make a partial class called patient that extended the patient class within the LINQ model. All the classes within LINQ 2 SQL are
generated using the partial keyword so you are able to extend them by just making another partial class with the same name.
(A little Gotha is that the to partial classes have to be in the same namespace or it will not work!)

 partial class Patient
    {
        public int TreatmentCount
        {
            get { return this.PatientTreatments.Count; }
        }
    }


Now my patients class from my LINQ 2 SQL DataContext will have a new property TreatmentCount which when called upon will
get a count of all treatments for the current patient.
WindowLinq

This is a basic overview of extending a LINQ 2 SQL model and is useful in situations where you are trying to create an easy to understand
API for you application. But don't forget extension methods which are really useful too and sometimes more appropriate when really trying
to bend the data to how want it!

Twitter Twitter Twitter Twitter Twitter
May 13, 2009 23:10 by DanWatson