0

I am working on an existing table where as I can see there are 3(!) primary keys: enter image description here

I want to copy the existing rows, alter the ctid column and then copy them again to the end of the table. I try that and I am getting the error:

Cannot add an entity with a key that is already in use.

Probably because I am copying the rows and adding them with the same primary keys. How I can solve this? Is it possible to solve it without modifying the db schema (I am thinking of adding ctid as primary key also)?

Code

var testsDefault = (from i in dc.TestUnits
                                       where i.ctid == null
                                       select i).ToList();

List<DAL.TestUnit> TestList = new List<DAL.TestUnit>();
                    foreach (var test in testsDefault)
                    {
                        DAL.TestUnit newTest = new DAL.TestUnit();
                        newTest.TestID = test.TestID;
                        newTest.PatientType = test.PatientType;
                        newTest.Unit = test.Unit;
                        newTest.ctid = "105";
                        TestList.Add(newTest);
                    }
                    dc.TestUnits.InsertAllOnSubmit(TestList);
                    dc.SubmitChanges();
aggelos
  • 67
  • 1
  • 11

2 Answers2

3

You need to add ctid to your composite primary key.

ALTER TABLE TestUnits
DROP CONSTRAINT PK_WhateverYourCompositeIndexNameIs

ALTER TABLE TestUnits
ADD CONSTRAINT PK_WhateverYourCompositeIndexNameIs PRIMARY KEY (TestID, PatientType, Unit, ctid)

See: How can I alter a primary key constraint using SQL syntax?

Joe Phillips
  • 49,743
  • 32
  • 103
  • 159
  • can you tell me how I can do this? – aggelos Jun 23 '17 at 14:09
  • 2
    Also be aware that changing the primary key could have a wide range of effects that you need to consider (for example, if your code previously expected to get one record by TestID/PatientType/Unit, it might now be getting 1+N records)... Query performance might change negatively, indexes/other queries may need to be reconsidered, etc. – Trioj Jun 23 '17 at 14:16
  • 2
    Also a 4-column composite primary key consisting entirely of text columns seems, well, sub-optimal to me. You may also want to consider refactoring to use a surrogate key. – Trioj Jun 23 '17 at 14:24
0

No,it is not possible what you are trying to do without modifying the db schema. Since you are using three PK and Primary key can not be duplicate as you are trying to do. The solution to your problem is make all the row's columns unique and then add the another row but make sure all tuples must have unique entries.

The another solution to your problem is already given by Rafalon