LINQ To SQL Attach Method for Attaching Detached Business Entities - DataContext.Attach

LINQ To SQL Attach Method for Attaching Detached Business Entities - DataContext.Attach

by David Hayden ( Microsoft MVP C# ), Filed: LINQ To SQL

 

Dinesh is trying to help developers understand the role and importance of the Attach Method in LINQ To SQL in the following post:

Attach() if you have something detached

If you are new to O/R Mappers and the concept of tracking the state of business entities and changes to those entities, it is worth reading.

It really comes down to a couple of things:

  • Is the entity new or a stale copy of something already in the database?
    • Important because it decides if and INSERT or UPDATE Command is Sent to the SQL Server Database
  • If a stale copy, what has changed?

The DataContext is keeping track of the state of business entities in LINQ To SQL, but many times the original DataContext is not available and hence state information and changes made to the business entity is lost. The Attach Method on the DataContext in LINQ To SQL helps you re-attach an existing business entity that came from the database as well as information about the original state of the entity to help with optimistic concurrency.

Unfortunately, this is not an exact science and imperfect in an imperfect world. Using a TimeStamp, which I used in my latest LINQ To SQL Application, avoided this problem. Unfortunately, this is not always available in an application that needs to target multiple databases or with legacy databases.

If you are serializing / deserializing business entities using web services or in general unable to use the original DataContext that keeps track of the state of business entities, I recommend understanding the limitations and functionality of the DataContext.Attach Method.

LINQ To SQL Tutorials

News Feed: David Hayden ( Microsoft MVP C# ), Filed: LINQ To SQL

posted on Friday, October 12, 2007 4:50 PM

My Links

Post Categories

Article Categories

Archives

Loose-Leaf Tea