Paul said:
Hi,
I have a DataContext with two classes, customers and orders.
In the DataContext i insert a new customer, but not execute a
SubmitChanges ().
How can i do to loop thought the Class "Customers" and find the new
customer inserted? (I can't update a Database)
Thanks
If you're using EF I don't know about Link-2-SQL but I suspect the same,
then you would use the System.Transaction namespace and do a Transaction
on your Insert.
You must do the SubmitChanges(). However, while in Transaction mode and
using the SubmitChanges(), one must do Transaction.Complete() after the
SubmitChanges() to commit the changes to the database.
After the SubmitChanges() but before the Transaction.Commit on an
AddToCustomer(customer), the object is written to the database but 'not
committed'. It's at this point that the ID of the new Customer object
has the key assigned to the Inserted Customer object.
You can address the key field property of the Customer object and get
the key just assigned to the new Customer object.
AddToCustomer(customer);
var ID = customer.ID; // you got the ID of the Customer object just
inserted.
Again, the object is NOT committed to the database when doing the
SubmitChanges(), until after the Transaction.Complete is done to commit
the changes to the database.
That also means that before you do the Transaction.Complete(), you can
query for the inserted Customer object using Linq based on its
'trapped' ID for the object, make changes to the Customer object after
the insert and update it.
You can do another SubmitChanges() after updating Customer.
But again, no changes are committed to the database, until the
Transaction.Complete has been done. If an exception is thrown, and it
never reaches the Trans.Complete(), then all changes to the database are
rolled back.