C# 3.0 in a Nutshell
C# 3.0 in a Nutshell, Third Edition A Desktop Quick Reference By Joseph Albahari, Ben Albahari
September 2007
Pages: 858


Welcome Guest ( Log In | Register )

 
Reply to this topicStart new topic
How To Delete An Entity Before Submitchanges ?
Bassam EG
post May 28 2009, 04:28 AM
Post #1


New Member
*

Group: Members
Posts: 4
Joined: 28-April 09
Member No.: 17,843



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
Go to the top of the page
 
+Quote Post
JoeAlbahari
post 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
Go to the top of the page
 
+Quote Post
Bassam EG
post May 29 2009, 02:04 PM
Post #3


New Member
*

Group: Members
Posts: 4
Joined: 28-April 09
Member No.: 17,843



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

Go to the top of the page
 
+Quote Post
JoeAlbahari
post 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
Go to the top of the page
 
+Quote Post

Reply to this topicStart new topic
2 User(s) are reading this topic (2 Guests and 0 Anonymous Users)
0 Members:

 

RSS Lo-Fi Version Time is now: 7th November 2009 - 01:07 PM