views:

58

answers:

3

I have some objects which have been created automatically by linq2SQL.

I would like to write some code which should be run whenever the properties on these objects are read or changed.

Can I use typical get { //code } and set {//code } in my partial class file to add this functionality? Currently I get an error about this member already being defined.

This all makes sense.

Is it correct that I will have to create a method to function as the entry point for this functionality, as I cannot redefine the get and set methods for this property.

I was hoping to just update the get and set, as this would mean I wouldn't have to change all the reference points in my app. But I think I may just have to update it everywhere.

A: 

Unless you modify the generated code that was made, and then add additional code to the setter (such as using the pattern like in WPF, with INotifyPropertyChanged), then this would be impossible.

Tejs
Yep, definitely don't want to be doing that, as then I lose the auto generation of the linq2sql niceness.
optician
+1  A: 

What I did when I wanted to do this was make the property private/inaccessible (since this can be done as part of the DBML definition without editing the generated code), and give it a different name than the property I want to expose. Then I implemented a public wrapper property in a partial class, using the name I wanted to expose. Then (if you want to be really fancy) implement a LINQ provider that can convert queries that refer to the wrapper properties to queries that refer to the underlying properties. I have done all this and it's been working well, but the custom LINQ provider was tricky.

BlueMonkMN
Also interesting, but I like the idea of being able to just used the dbml auto generated version, without having to keep track of modifications. However the stuff towards the end of your post goes a bit over my head for the mo.
optician
Yes, I like not having to modify the code generated by the DBML. This solution allowed me to wrap the properties without having to touch the DBML-generated code. Hopefully the stuff towards the end is unnecessary. You would only need to do that if you wanted to use the wrapped propertied when performing LINQ-to-SQL queries directly against the database rather than retrieving some records (without using those properties) and then querying/filtering the list of objects you retrieved with LINQ to Objects.
BlueMonkMN
+2  A: 

Not sure about read, but you could track changes of your objects. E.g. there is PropertyChangedEventHandler on auto generated entities.

So what have you do is to white a partial class (let's assuming you have a Person entity):

public partial class Person
{
    public Person()
    {
        this.PropertyChanged += 
           new PropertyChangedEventHandler(Person_PropertyChanged);
    }

    protected void Person_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        // your code here
    }
}
Alex