The reason is mainly because see the blog park and friends began to discuss Linq2sql, this time it is attach. By interpreting attach, you can discover how the Linq2sql internally maintains and tracks object instances, how to implement deferred loading, and also raises discussions about the application techniques of deferred loading and linq2sql in N-tier application. The content discussed in this article applies to the Linq2sql of the. Net Framework version 3.5, where the database used is Northwnd.
For object add and delete operations, Linq2sql directly provides InsertOnSubmit ()/deleteonsubmit () in the Table<t> class definition. As for the update of the object, because of the mechanism of object tracking in Linq2sql (refer to Linq2sql Object Lifecycle Management), we do not need to explicitly notify the DataContext after modifying the object properties. When Datacontext.submitchanges () is invoked, the changes we make are automatically submitted to the database for saving. This context-based operation is convenient, otherwise there will be a large number of update calls in the code, but there are restrictions-only in the scope of the same DataContext object that the modifications made by the object are saved at SubmitChanges (). Such as:
1 using (var context = new Northwnd())
2 {
3 var customer = context.Customers.First();
4 customer.City = "Beijing";
5 context.SubmitChanges();
6 }
In the development of web and n-tier application, data query and update are often not satisfied in a DataContext, so Linq2sql defines table<t> method in attach class. Used to associate an object that has been disconnected from the query DataContext context to the DataContext object to which the table belongs, so that the update operation of the object can be performed with the new DataContext. Such as:
01 Customer customer = null;
02
03 using (var context1 = new Northwnd())
04 {
05 customer = context1.Customers.First();
06 }
07
08 customer.City = "Beijing";
09
10 using (var context = new Northwnd())
11 {
12 context.Customers.Attach(customer);
13 context.SubmitChanges();
14 }
But here's the problem, this code executes the error and throws the following exception:
System.NotSupportedException:An attempt has been made to Attach or Add a entity that isn't new, perhaps having been loa Ded from another DataContext. This isn't supported.
The problem is not a new one, Google has a lot of solutions, but why does this seemingly normal code throw an exception? In fact, it is related to the scope of DataContext, this article tries to dissect this problem, and then discusses some tips for using Linq2sql in N-tier application.