Using Storage Attribute to bypass property accessor

For every column in the database, linq to SQL generates a property that maps a particular column in the database to the property defined on the entity class. However if you look at the setter property generated by the designer, it has all the details which raises events that notifies to the subscribers that property has changed. Basically for a property called ProductName, the designer generated code will raise a before and after event. Further more the setter also notifies the tracking service that property has been changed by the end user code. Due to this reason, linq to SQL is able to generate the appropriate SQL statement to send the changes to the database. However, when we fetch an entity from the database, linq to SQL has to go through the same process of assigning the property value by reading the column from the database, which is totally not required. We do not want linq to assign our property using the setter because the values assigned would be tracked and there is no point in tracking the value since it was not changed by the end user code. This is where we can use the attribute called Storage which specified the private level variable that linq to SQL can directly use to by pass property accessors and interacts directly with our field level variable.  By default the designer ensures this for your by making use of Storage Attribute. However there is nothing stopping you from changing this behavior if you want linq to SQL to use property accessors and go through your business logic defined inside your setter. Here is a an example of the code generated by the linq to SQL designer.

image

1 Comment

Comments have been disabled for this content.