How To Delete An Entity Before Submitchanges ? |
![]() ![]() |
How To Delete An Entity Before Submitchanges ? |
May 28 2009, 04:28 AM
Post
#1
|
|
|
|
Hello, I have this simple code using LINQ to SQL :
Customer c = New Customer { Name = "C1", Age = 22 }; Customer c1 = New Customer { Name = "C2", Age = 20 }; ctx.Customers.InsertOnSubmit( c ) ctx.Customers.InsertOnSubmit(c1) \\now the 2 new entities are in the datacontext , i want to remove the second customer - for whatever reason like if a user discovered that he entered it by error - I want to do that before i submit changes DeleteOnSubmit will give an exception because those 2 entities are not tracked by the datacontext yet because they are new, their status is UnTracked this sound very simple but i can't find a answer for it !! Thank you Bassam This post has been edited by Bassam EG: May 28 2009, 04:30 AM |
|
|
|
May 28 2009, 05:36 PM
Post
#2
|
|
|
Advanced Member ![]() ![]() ![]() ![]() ![]() ![]() Group: Members Posts: 203 Joined: 15-February 08 From: Perth, Australia Member No.: 90 |
The answer is to call DeleteOnSubmit. It should NOT throw an exception - have you tried it?
Regards Joe |
|
|
|
May 29 2009, 02:04 PM
Post
#3
|
|
|
|
Hello,
indeed, it works ! , i was confused by reading this link on DeleteOnSubmit: http://msdn.microsoft.com/en-us/library/bb386982.aspx saying that: You can call DeleteOnSubmit only on an object tracked by the DataContext. For an Untracked object, you must call Attach before you call DeleteOnSubmit. Calling DeleteOnSubmit on an Untracked object throws an exception. and at the same time defining Untracked object as: An object not tracked by LINQ to SQL. Examples include the following: An object not queried through the current DataContext (such as a newly created object). --------- Can you kindly advice what that means if it indeed works regardless of the article rule Thank you very much for your time Bassam |
|
|
|
May 29 2009, 09:55 PM
Post
#4
|
|
|
Advanced Member ![]() ![]() ![]() ![]() ![]() ![]() Group: Members Posts: 203 Joined: 15-February 08 From: Perth, Australia Member No.: 90 |
A new object is tracked as soon as you call InsertOnSubmit or Attach on it.
It's also tracked if you add it to an EntitySet, or if it was a mapped entity that originally came from a Table<T> or a LINQ-to-SQL query. Regards Joe |
|
|
|
![]() ![]() |
|
Lo-Fi Version | Time is now: 7th November 2009 - 01:07 PM |