Solved

LINQ SubmitChanges confusion!!!

Posted on 2011-03-06
13
747 Views
Last Modified: 2013-12-17
I create a new object, and try to submit the changes.  In the SubmitChanges() call, an exception gets thrown because of a unique constraint violation.  I fix the error and try to re-submit and get this error:

"An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext."

How is this "meant" to be done?

// Create the object, and the data context
User user = new User();
user.Name = "test";
user.Username = "test";
user.Password = "pwd";
WDB db = new WDB();
db.Users.InsertOnSubmit(user);

// Try to submit the data
try {
   db.SubmitChanges();
} catch { 
  // unique constraint violation on Username field
  user.Username = "test2";  // Fix constraint violation
  db.SubmitChanges(); // Generates the error above ?? WTF ??
}

Open in new window

0
Comment
Question by:kalliopi
  • 6
  • 4
  • 2
  • +1
13 Comments
 
LVL 21

Expert Comment

by:naspinski
ID: 35047703
You must have the Username fields set as UNIQUE in your database and there is already an entry "test2"
0
 
LVL 6

Author Comment

by:kalliopi
ID: 35058390
Thanks naspinski.

I have the Username field set as Unique in my database but there is NOT already a test2.  That's the whole problem.  

There IS a 'test' username - so I get an exception (as I would expect) when I go to submit the changes, because it violates the unique constraint.

So - I fix the problem, and try to re-submit, and get this (what I think is a kind of "funky") error about Attaching to a datacontext.  Why isn't my object still "new"?  The user didn't get inserted the first time I called SubmitChanges, it should still be new, and the 2nd SubmitChanges "should" work imho... no?  

Obviously I'm misunderstanding something, but I can't figure out what...
0
 
LVL 62

Accepted Solution

by:
Fernando Soto earned 500 total points
ID: 35058915
Hi kalliopi;

I just created a test database and ran your code against it and it ran as expected. The first SubmitChanges failed and the second SubmitChanges worked with no issues. This is the code I used.

            // Create the object, and the data context
            User user = new User( );
            user.Name = "test";
            user.Username = "test";
            user.Password = "pwd";

            DataClasses1DataContext db = new DataClasses1DataContext( );

            db.Users.InsertOnSubmit( user );

            // Try to submit the data
            try
            {
                db.SubmitChanges( );
            }
            catch
            {
                // unique constraint violation on Username field
                user.Username = "test2";  // Fix constraint violation
                db.SubmitChanges( ); // Generates the error above ?? WTF ??
            }

Open in new window


If you can create a test project with test database that shows the issue I will look at it. If follow the following instructions:

Can you zip the complete project and upload it. Please use the EE site below it will not give you issues with file types,

To upload a file in zip format to the Experts Exchange Stuff web site at http://www.ee-stuff.com follow these steps:

1.  Zip the files or project to be uploaded
2.  The go to http://www.ee-stuff.com
3.  If you are prompted to log in use the same username and password you use on the main site here
4.  At the top of the page click on "Expert Area" tab
5.  Then click on "Upload a new file" link
6.  Follow the instructions on the page
7.  After a successful upload post the link of the file in the question.

Fernando
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
LVL 6

Author Comment

by:kalliopi
ID: 35073678
First of all - thanks.  It's very helpful to know that this worked for you.  The code I posted was VERY close to my actual code, but obviously I'm losing something in the translation.  I will try to put together a sample project that illustrates this issue - but my guess is that my question will get answered in trying to do so...

If it doesn't, I'll post the zip file as requested.  Thanks - I'll be in touch.
0
 
LVL 2

Expert Comment

by:cyrusjoudieh
ID: 35117073
This is a working version;
       
//Use New Connection
 dbContext db = new dbContext("metadata=res://...");

 TUser user = new  TUser();
 user.Name = "test";
 user.Username = "user";
 user.Password = "pwd";
 try
 {
   db.AddToUsers(user);
   //Throws (Violation of PRIMARY KEY constraint)
   db.SaveChanges();
 }
 catch
 {
   user.Name = "test2";  //Make sure the unique name does not exist, it should not throw an error
   db.AddToUsers(user);
   db.SaveChanges(); //Get Saved.
 }
0
 
LVL 6

Author Comment

by:kalliopi
ID: 35186626
So I can't reproduce it outside of my app.  I've setup a separate project, with the same database, same table structure, same code.  In my app, I get the error.  In the test project, it works as expected.

This looks like exactly the same problem I'm having, but again, there's no solution here either:
http://social.msdn.microsoft.com/Forums/en/linqtosql/thread/8a68e80a-25e5-489f-982a-3946136d3107

I can't see ANYTHING that I'm doing differently.  And yet, I'm getting the error above.  I'm totally confused.
0
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 35189490
Hi kalliopi;

Then it may be possible that there is a problem with the solution files. Have you tried to Clean the solution by doing the following, on the main menu of the IDE click on the following "Build -> Clean Solution", then recomiple and try again.

Fernando
0
 
LVL 6

Author Comment

by:kalliopi
ID: 35189729
I have cleaned it.  I have not yet stripped it down piece by piece to figure out what the problem is.  It's not a huge app, but it's big enough that this would take a few hours to do...
0
 
LVL 2

Expert Comment

by:cyrusjoudieh
ID: 35189919

1- Are you sure that the name is unique in that database not in test project.
2- This technic should be avoided, and the user unique name should be checked prior saving to database, if not unique show error to user before saving.
3- Try to recreate a new connection and add the new entity.
0
 
LVL 6

Author Comment

by:kalliopi
ID: 35204513
1) Yes - the name IS unique
2) This was just a test.  In the actual app, the user will be notified as you suggest.  I'm just trying to figure out how to recover from an error in linq, and was surprised that the error could not be corrected and resubmitted (for some reason).  Again - in my test project, it works as expected, but for some reason, in this specific case, I'm getting the error mentioned.
3) This works.  I only get the error when there is first an exception.
0
 
LVL 2

Expert Comment

by:cyrusjoudieh
ID: 35213598
Try issuing an additional parameter to SumbitChanges:

ConflictModes:

1- FailOnFirstConflict:
Will always throw an error until a new connection is created
db.SubmitChanges(ConflictMode.FailOnFirstConflict);

2- ContinueOnConflict:
You will be able to do changes and save.
db.SubmitChanges(ConflictMode.ContinueOnConflict);

0
 
LVL 2

Expert Comment

by:cyrusjoudieh
ID: 35213681
Sorry: those are the correct definitions of the two conflict modes.

FailOnFirstConflict : Specifies that attempts to update the database should stop immediately when the first concurrency conflict error is detected.  

ContinueOnConflict:  Specifies that all updates to the database should be tried, and that concurrency conflicts should be accumulated and returned at the end of the process.  

http://msdn.microsoft.com/en-us/library/bb345922.aspx

0
 
LVL 6

Author Closing Comment

by:kalliopi
ID: 35443016
I have been unable to figure out where this error came from.  A "clean" version behaved as described, but the version in my app still throws the odd error - and I have found others on the web that have the same problem.  Strange!
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Parsing a CSV file is a task that we are confronted with regularly, and although there are a vast number of means to do this, as a newbie, the field can be confusing and the tools can seem complex. A simple solution to parsing a customized CSV fi…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …

786 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question