I have created table with Composite Primary Key, but while edit giving Integrity constraint violation error in cakephp.
Integrity constraint violation : 1062 Duplicate entry while saving Composite Primary Key data of model
Integrity constraint violations mean that you are trying to save a duplicate of a Unique value in the database. Primary Keys have to be Unique.
Do you have your Primary Key field in your database set to auto increment? If you do not, that may be your problem.
Otherwise, when you insert a record, it's probably going to insert a row with PK of 0. Then when it tries to insert another record, it will try to insert another row with PK of 0, thus not being unique, and throwing the Integrity Constraint violation.
However
You mentioned that you are doing an edit. If you are doing an edit, then you are not passing the edited rows Primary Key when you are saving it to the database, so cake tries to do a CREATE instead, thus resulting in another duplicate row ID.
Make sure you do this:
$this->Model->id = $id; // Where $id is the Primary Key of the row being edited.
Conversely, you can also do this:
$data['Model']['id'] = $id;
$this->Model->save($data);
You can capture the $id by either storing it as a hidden field in your edit form, or as a URL parameter passed to the action.
Related
I have a table defined in Sql Server with a GUID primary key and a default of newsequentialid():
CREATE TABLE [dbo].[mything](
[id] [uniqueidentifier] NOT NULL,
[foo] [varchar][32] NULL,
CONSTRAINT [PK_mything] PRIMARY KEY CLUSTERED
(
[id] ASC
)
)
GO
ALTER TABLE [dbo].[mything]
ADD CONSTRAINT [DF_mything_id]
DEFAULT (newsequentialid()) FOR [id]
GO
And when I add an entity with the guid primary key already set, it ends up as a record in the database with a new guid primary key.
var anEntity = new mything
{
id = "17870C25-FC04-EB11-80E9-000C29F38B54",
foo = "Some stuff",
}
dbContext.mythings.Add(anEntity);
dbContext.SaveChanges();
EF seems to ignore the guid that was provided in the record and writes the record with a new Guid.
What I would expect is that the record provided had a null guid, it would be populated with a new guid, and if it was not null it would be used unchanged. But that's not what I'm seeing happen.
I'm seeing duplicate records, with different GUIDs, instead of primary key violation exceptions, because the GUIDs I'm providing in my EF entities are being ignored.
Why could this be happening?
Please tell me this isn't by design!
===
OK, this does seem to be by design.
First, this isn't in SQL server. If I try to insert a record with the id field set, it inserts, or fails with a primary key failure if there is already a record with that id. It only creates a new GUID for the id field if the provided id field is null.
But in EF, the value in the id field is ignored, and a new GUID is generated every time.
It was suggested to me that EF was behaving this way so as to follow the same pattern as when using autoincrement keys. And that does seem to be the case.
In SQL Server, if you try to provide a value to an autoincrement key field on an insert, you get an error:
Cannot insert explicit value for identity column in table
But in EF, the value you provide is ignored, and a new value is generated.
So in this respect, Entity Framework is consistent. Consistently wrong, but consistent.
First step I'd look at to narrow this down is to capture a Profiler/Extended Event trace at the database to see exactly what EF is sending to the database.
Your expectation of the database behaviour is correct - so I'd want to understand where it is breaking down first
Use Case:
I am performing performance execution on an database and I am trying to do following:
I took an backup of the database (the mdf and ldf file) at the early stage (lets called a "baselinecopy").
After that I execute some performance script .And the database reach to baselinecopy+Additional_Row (let it be "NewDatabase") from the test.
Then I replace the database baselinecopy with NewDatabase & start the server. While trying to perform operation on application it is giving me Violation of PRIMARY KEY constraint to test_order. Cannot insert duplicate key in object.
I check the "IDENTITY" but the table has no identity set.
Any thoughts on this ?
Violation of PRIMARY KEY constraint to test_order. Cannot insert duplicate key in object.
This is exactly what it says.
You have defined a primary key on a table and are attempting to insert a record that contains the same primary key as an existing record.
It does not need to be an identity column to be a primary key column.
I'm trying to learn SQL Server and got confused about use of foreign key. I'm good with creation, altering and dropping the foreign keys., by my doubt is that when the Foreign key is useful!
1st table is 'subject', having 'subject'(primary key) and 'teacher' in it.
2nd table is 'Class', having 'Class'(primary key) and 'Floor'.
I made the 3rd table 'Details' with 'class' and 'subject'.
'details.subject' is the foreign key reference to 'subject.subject AND 'details.class' is the foreign key reference to 'class.class'. Now Im confused how can I see all the details in one excecution?
SELECT *
FROM Details
is giving only class and subject from the table 'Details'. But I want to get " details.class, class.floor, details.subject, subject.teacher " when I run a singe query. If we get the mentioned output only if we use 'JOINS', then why we should use 'Foreign Key' :o
I think you understand my doubt.. Im stuck, Please help :p
It is used to prevent actions that would destroy links between tables. The FOREIGN KEY constraint also prevents invalid data from being inserted into the foreign key column, because it has to be one of the values contained in the table it points to.
Also you if you have foreign key relation ship between 2 tables. And you have enabled cascade on deletion then if parent row deleted it will automatically deletes related row in child table.
I have got a database with stores and rental copies. Each rental copy is assigned to a store. I would like to create a trigger which, if you delete a certain store, it will assign all copies from that store to another , predefined store (cvr).
I have tried like this:
CREATE OR REPLACE TRIGGER delete_trig
BEFORE DELETE ON Store
FOR EACH ROW
BEGIN
UPDATE RentalCopy SET cvr = 123456789
WHERE cvr = :old.cvr;
END;
I get an error which says I have violated a previously added constraint (which takes care of the foreign key between these 2 tables) , as it has found a child record. How can I fix it?
Table definitions for these tables: (relevant part)
RentalCopy:
barcode INTEGER NOT NULL,
CVR INTEGER NOT NULL,
PRIMARY KEY(barcode),
CONSTRAINT fk_storeinfo
FOREIGN KEY (CVR) REFERENCES Store
Store:
CVR INTEGER NOT NULL,
store_name VARCHAR2(30) NOT NULL,
PRIMARY KEY(CVR)
Looking at your code, it seems like your table RentalCopy is connected to Store by a foreign key on the column(s) CVR of both the tables.
So, a CVR value in RentalCopy must have a corresponding cvr on the Store table, failing which you will get a foreign key error.
The error you are getting is possibly because you are trying to delete/update a cvr record from Store
(because then the forign key for the table RentalCopy has no cvr as child in Store table), and not because of any trigger syntax error
I'm having trouble figuring out how to create a foreign key constraint. My data model is fixed and out of my control, it looks like this:
CREATE TABLE Enquiry
(Enquiry_Ref INTEGER PRIMARY KEY CLUSTERED, Join_Ref INTEGER, EnquiryDate, EnquiryType...)
CREATE TABLE Contact
(Contact_Ref INTEGER PRIMARY KEY CLUSTERED, Surname, Forenames ....)
CREATE TABLE UniversalJoin
(Join_Ref INTEGER, Contact_Ref INTEGER, Rel_Type INTEGER)
Each Enquiry has exactly one Contact. The link between the two is the UniversalJoin table where
Enquiry.Join_Ref = UniversalJoin.Join_Ref AND
Rel_Type = 1 AND
UniversalJoin.Contact_Ref = Contact.Contact_Ref
The Rel_Type differs depending on what the source table is, so in the case of Enquiry, Rel_Type is 1 but for another table it would set to N.
My question is how do I create a foreign key constraint to enforce the integrity of this relationship? What I want to say, but can't, is:
CREATE TABLE Enquiry
...
CONSTRAINT FK_Foo
FOREIGN KEY (Join_Ref)
REFERENCES UniversalJoin (JoinRef WHERE Rel_Type=1)
You can't use conditional or filtered foreign keys in SQL Server
In these cases, you could have a multiple column FK between (JoinRef, Rel_Type) and set a check constraint on Rel_Type in UniversalJoin to make it 1.
However, I think you are trying to have a row with multiple parents which can't be done.
You might rather want to have a look at CHECK Constraints
CHECK constraints enforce domain
integrity by limiting the values that
are accepted by a column. They are
similar to FOREIGN KEY constraints in
that they control the values that are
put in a column. The difference is in
how they determine which values are
valid: FOREIGN KEY constraints obtain
the list of valid values from another
table, and CHECK constraints determine
the valid values from a logical
expression that is not based on data
in another column.
You could use a table trigger with INSERT and Update to layer the equivalent as a FK.
This way you are able to apply conditions i.e. if column value =1 check exists in table a if column value = 2 then check another table.