views:

388

answers:

2

I am trying to extend my Linq-to-Sql entity with a few extra properties. These are "calculated" properties based on data from the underlying SQL View. For example, think of having a Date of Birth field, which is used to calculate an extended Age field.

I tried to extend my entity class by extending the OnLoaded() method.

I get a compile time error however stating that I cannot create it. I checked the designer code for my LTS entity class, and it doesn't have a partial definition for any of the expected extension points.

I checked a few of my other LTS entity classes and they do have these extension points. The only difference I see is that the one without is loaded from a SQL View, rather than a table. Is there a way to hook into a "Loaded" event when loading from a SQL View?

TIA!

+1  A: 

You can do this by means of a property. Just create a partial class with the same name as your entity. Any properties or methods that you add will automatically be part of the entity and allow to use any of its members.

Here's an example of the pattern:

public partial class [The Name of the Entity]
{
   public int Age
   {
      get
      {
         return CalculateAge(this.DateOfBirth);
      }
   }
}

Here's some logic on how to calculate the Age (Source: Geekpedia)

public static int CalculateAge(DateTime BirthDate)
{
    int YearsPassed = DateTime.Now.Year - BirthDate.Year;
    // Are we before the birth date this year? If so subtract one year from the mix
    if (DateTime.Now.Month < BirthDate.Month || 
          (DateTime.Now.Month == BirthDate.Month && DateTime.Now.Day < BirthDate.Day))
    {
        YearsPassed--;
    }
    return YearsPassed;
}
Jose Basilio
Yeah, was trying to avoid this because the calcs that I do actually do quite a bit more than calculate the age and I wanted to avoid having to recalculate each time the property is called. I know I can get around that with a check to first see if age has already been calculated, but was hoping to not have to "pollute" my code with all kinds of "if (myValue != null)" checks.
Brian
+2  A: 

I found that I did not have a PrimaryKey specified for my Linq-to-Sql entity class. I believe without a Primary Key specified, no extension methods generated in the entity class. Once I specified a Primary Key on my LTS entity class definition (through the designer), I was able to extend the OnLoaded() event.

Brian