Question

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!

Was it helpful?

Solution

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.

OTHER TIPS

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top