Auto-computed properties in Linq 2 Sql objects?

Let's say I have a table in my database called Orders that has the following columns:

OrderId Order Date CancelDate ShipDate LastActionDate

I want LastActionDate to always be the last date of OrderDate, CancelDate and ShipDate. What's the best way to do this? Is there a way to handle the OnChanged event of these three dates so that the LastActionDate can be recalculated when these properties change? Or is there some built in Linq 2 Sql magic that handles this scenario? Or do I just need to make sure to set the LastActionDate when I change any of the three dates?

+2


source to share


2 answers


In your Linq-to-SQL model, every property of every object has a partial method called "(property name) Modified ()".

Partial methods - a new feature in C # 3.0 - are methods that are defined but don't necessarily have a real implementation. If they don't have an implementation, any call to them will be removed during the link phase of the build process.

However, if you provide an implementation, then that implementation is actually called. Since your object classes such as Order

are partial classes, you can easily create your own additional partial class and define these methods.

So, in your case, you will find OrderDateChanged()

, CancelDateChanged()

and ShipDateChanged()

.



From these methods, you can easily call a method called CalculateLastActionDate()

that will calculate your new date as needed. Should be pretty easy.

public partial class Order
{
   void OrderDateChanged()
   {
       CalculateLastActionDate();
   }

   ......

   private void CalculateLastActionDate()
   {
      ... your implementation here
   }

}

      

Mark

+1


source


If you want LastActionDate to be calculated, you shouldn't have it as a column in your database.

Assuming the column is not in the database, it should not be part of the autogenerated L2S code either. This is good because it means you can add it yourself as the auto-generated L2S classes are partial classes.

Add new C # code and declare the Order class with the same signature as the auto generated Order class and add your computed property. Something like that:



public partial class Order
{
    public DateTime LastActionDate
    {
        get
        {
            // pick the desired value from the other
            // three properties and return it
        }
    }
}

      

Pay attention to the keyword partial

in the class declaration.

0


source







All Articles