Why Linq to sql can't keep track of update information if we directly assign new object value to old one?

I have the following code

Customer customer = (from x in db.Customers where x.CustomerID.Equals(cust.CustomerID.Value) select x).SingleOrDefault();

customer = newcustomer;
db.SubmitChanges();

      

by executing the above code, I can get new data into the client object, But by doing it SubmitChanges()

, it cannot update in the database.

I need to write the following kind of mechanism to update a value in a database.

customer.CustomerName = "James";
customer.DisplayName = "Jimmy";

db.SubmitChanges();

      

Are there any suggestions for this?

+3


source to share


2 answers


You cannot do this because you are changing the link it points to customer

. So the ORM loses the changes you made to the object that you check out from the database. In fact, when you grab a record from the database for a specific client like below:

Customer customer = (from x in db.Customers 
                     where x.CustomerID.Equals(cust.CustomerID.Value) 
                     select x).SingleOrDefault();

      

You create an object whose properties have the values ​​found in the record you retrieved. When later you change, for example, the valueCustomerName

customer.CustomerName = "James";

      



and then you call the method SubmitChanges

:

db.SubmitChanges();

      

a process is executed that detects any changes made to the object. This process detects that you have changed the value CustomerName

and the appopriate UPDATE statement will be generated by the ORM. The last statement is sent to the database for execution.

On the other hand, if you change the value customer

, the change detection process decides that nothing has changed relative to the retrieved record. Why this is because the only way the ORM knows the record is by the reference it has to the created object after retrieving. By changing this, you are losing it out of your context.

+1


source


If you see msdn , you will get a response.

No matter how many changes you make to your objects, changes are made to in-memory replicas only. You have not made any changes to the actual data in the database

When you call SubmitChanges, LINQ to SQL checks the set of known objects> to determine if new instances have been added to them. If present,> these new instances are added to the tracked object set.

There are 2 statements

customer = newcustomer;

      



this statement simply updates the value or reference in memory.

db.SubmitChanges();

      

This statement commits all changes by inserting, updating, deleting the statement in memory to the end of the db with a proper commit commit.

Therefore, we need to use the second operator whenever we need to force and update data.

0


source







All Articles