Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 889489
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T13:34:34+00:00 2026-05-15T13:34:34+00:00

The code listed below attempts to update a row in the database, but throws

  • 0

The code listed below attempts to update a row in the database, but throws an exception instead:

System.Data.Linq.DuplicateKeyException:
Cannot add an entity with a key that
is already in use

Most examples I’ve seen query the database to obtain an instance of an entity, modify some of the instance’s properties, and then update it. Here I’m getting the object from a different source entirely (it’s being parsed from an XML file) and querying to see if there’s already a row for this data. If there is, I’m setting the primary key and attempting to run an update. What’s the correct way to do this?

Here’s the trimmed down version of the code:

Customer customer = new Customer(); // Customer has a database generated
                                    // identity column called CustomerId

// populate customer object
customer.Name = "Mr. X";
customer.Email = "x@company.com";
// etc.

// is customer already in database?
// identify customer by email
var results = ctx.Where(c => c.Email == customer.Email); // ctx is a DataContext

if (results.Any())
{
   Customer existing = results.Single();

   // set primary key to match existing one
   customer.CustomerId = existing.CustomerId;

   // update database
   customerTable.Attach(customer);  // customerTable is a Table<Customer>
   ctx.SubmitChanges();
}

// otherwise do insert
// ...   
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T13:34:34+00:00Added an answer on May 15, 2026 at 1:34 pm

    Apparently this is not a new problem. Here’s a sampling of some of the posts that discuss this issue:

    http://www.west-wind.com/weblog/posts/134095.aspx

    http://www.codeproject.com/KB/linq/linq-to-sql-detach.aspx

    http://social.msdn.microsoft.com/forums/en-US/linqprojectgeneral/thread/3848c02c-464e-40ff-87b6-813bff7b1263/

    I got it working by creating a new DataContext and Table before doing the update. My modified code looks like this:

    Customer customer = new Customer(); // Customer has a database generated
                                        // identity column called CustomerId
    
    // populate customer object
    customer.Name = "Mr. X";
    customer.Email = "x@company.com";
    // etc.
    
    // is customer already in database?
    // identify customer by email
    var results = ctx.Where(c => c.Email == customer.Email); // ctx is a DataContext
    
    if (results.Any())
    {
       Customer existing = results.Single();
    
       // set primary key to match existing one
       customer.CustomerId = existing.CustomerId;
    
       // **** CODE CHANGES HERE ****
       // create new DataContext and table to avoid DuplicateKeyException errors
       var ctx = new DataContext(customerTable.Context.Connection.ConnectionString);
       customerTable = ctx.GetTable<Customer>();
    
       // update database
       customerTable.Attach(customer);  // customerTable is a Table<Customer>
    
       // **** ANOTHER CODE CHANGE ****
       // without this line the data won't be updated with the new values
       ctx.Refresh(RefreshMode.KeepCurrentValues, customer);
    
       ctx.SubmitChanges();
    }
    
    // otherwise do insert
    // ...  
    

    The way I understand this is that the DataContext can only contain one instance of each unique entity. Attempting to attach a new entity with the same primary key causes the error, as there will now be two instances of the same entity. The new DataContext does not know about the existing entity and so has no problem attaching the new one.


    UPDATE: It looks like this question has already been answered.


    UPDATE: Don’t use my sample code as-is. It caused me other problems.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 469k
  • Answers 469k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer This may be what you need: http://sandbox.leigeber.com/fader/fader.html Code: http://www.leigeber.com/wp-content/uploads/2008/05/fader.zip May 16, 2026 at 2:43 am
  • Editorial Team
    Editorial Team added an answer The key argument to sort specifies a function of one… May 16, 2026 at 2:43 am
  • Editorial Team
    Editorial Team added an answer You're right! /Library for more generic classes. Like the ones… May 16, 2026 at 2:43 am

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.