"Violation of PRIMARY KEY constraint” when Inserting in database - c#

I'm trying to insert a record in database from a winform it was working fine and insert first 5 records with no error but when i try to insert next record it give me the error of Violation of PRIMARY KEY....!
The table is
But in Database table there is not record of no 6.
There is no trigger associate to this table.
there is no F-Key relationship of that table.
I tried it from sql server to insert it but again error.
What is the reason behind it?

There is definitely something wrong with your data. Please make sure you don't have a "duplicated PK" inserted.
And in my opinion, the PK should be generated automatically unless you have some special requirements.

You can fix this error by not trying to insert rows with a duplicate primary key.

Primary key should be auto generated.if you are getting this error then check your data first.

Primary key musty be inserted in table by itself, as this also reduces the code error chances that sometimes we try to insert same key again and again, (which is not the property of PK).
Also in database:
table> design> Primary Key> Properties>Identity specification> Yes
This will enable self insertion of key, also you can specify start index.

Related

Errors trying to add users to database using asp.net and c# in visual studio

Like when I add the First name, Last Name, Username and Password. For some reason I cant get it to let me add entries such as the UserId to say 1, 2, 3 and so on with the rest of the information
Instead I am getting this error when I try to register another person or make another entry to GridView1:
An exception of type 'System.Data.SqlClient.SqlException' occurred in
System.Data.Linq.dll but was not handled in user code. Additional
information: Violation of PRIMARY KEY constraint
'PK__User__1788CC4C1B5B052D'. Cannot insert duplicate key
User Table
Registration
Registration website
Error Message
I might not have explained this well. Forgive me.
loggedincode
logincode
linqtosql
Debugger
1) Make the column identity: Go to column property and set Identity specification and Is Identity: make it yes and increment by value 1
OR by:
UserID INT IDENTITY(1,1) PRIMARY KEY
2) Check your ID property inside the Item class to ensure that it have attributes like this:
[Column(Storage="_ID", AutoSync=AutoSync.OnInsert,
DbType="INT NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
Look at the IsDbGenerated=true, it is the important guy here.
Maybe you created the DatabaseContext using the designer before adjusting the IDENTITY on the Sql Server, so just regenerate this class (by deleting the table in the designer and dropping it from the Server Explorer again).
OR
In your LINQ to SQL designer, you need to make sure your column is set to:
Auto Generated Value = TRUE
Auto-Sync = ON INSERT
Hope this will help:)
So looks like your Key isn't auto populated.
This will cause a big issue because a primary key can't be null.
In your create table TSQL in picture "User table"
change the line to:
[UserID] INT NOT NULL
to
UserID INT IDENTITY(1,1) PRIMARY KEY
That should fix your problem
Caz
You are getting that error is because your User table's primary key column is not set to be an identity column. You are not setting the value of this column from your C# code, but the default is zero. Most likely you inserted one record successfully so a record with zero as the primary key got inserted. Now you are trying to insert more rows and another zero is going in so it is throwing that exception.
Fix
Make sure your User table's primary key is set to an indentity column so it auto increments. If you do not want it to be identity and increment automatically, then you need to pass the value in but you have to make sure it is unique or you will get the same error. I would just make it identity.

C# How can I clear all foreign key references in order to save the deletion of the primary key record to the database?

When I perform a delete on a primary key record it deletes the foreign key record and saves the change, but when it goes to delete the primary key record it won't let me save the deletion of the primary key record to the database. Instead it gives the following error:
Error: The primary key value cannot be deleted because references to this key still exist. [ >Foreign key constraint name = FK_PERSONID ]
According to what I've seen online I should be able to disable the EnforceConstraints either through code or through the DataSet Designer View. After doing it through code failed I tried changing the EnforceConstraints to False in the DataSet Designer View. It still gives the same error. I tried editing the foreign key constraint to do a Cascade Delete and it still gives the same error.
Trying to do it with only the Cascade Delete without the code got the same error.
This is the portion where I perform the deletes.
bizDocStartupDBDataSet1.EnforceConstraints = false;
BizDocStartupDBDataSet1.EmployeeTitlesRow oldEmployeeTitlesRow;
oldEmployeeTitlesRow = bizDocStartupDBDataSet1.EmployeeTitles.FindByPERSONIDCOMPANYID(currentPersonID,1);
oldEmployeeTitlesRow.Delete();
this.employeeTitlesTableAdapter.Update(this.bizDocStartupDBDataSet1.EmployeeTitles);
this.Validate();
this.employeeTitlesBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.bizDocStartupDBDataSet1);
this.peopleProfilesBindingSource.RemoveCurrent();
SaveData();
bindingNavigatorDeleteItem.Enabled = true;
bizDocStartupDBDataSet1.EnforceConstraints = true;
The SaveData function is just the standard save with a refilling of the table, but the change to the datatable can't be saved to the database because there are still references to the Foreign Key.
How do I clear out all the references to the foreign key after the key with the foreign record has been deleted so I can save the deletion of the primary key record to the database?
Foreign keys are used to prevent records from getting orphaned, so getting rid of the foreign key is only a solution when you didn't need it in the first place. Having said that, you'll have to cascade your deletes and you start with the record in the table that contains the foreign key, delete that FIRST, then delete the record with the primary key. You may have to make two dataadapters the way you're doing it, but ideally you'd do this all with a stored proc.
If you have binded tables be sure you are not delete records from the primary table unless you don't use them anymore.
if there is another table that contains a foreing key of the record you are trying to delete it you will have that problem.
Delete those record that are foreign keys of that record you want to delete and then at last delete that record you actually want to delete.
So i guess you should be careful of what you are trying to delete. Hope it helps!
And for the last question: you will have to delete all the records that are foreign.
EnforceConstraints is a property of a C# DataSet object. Modifying this value will not affect the structure or behaviors of your database.
Cascading delete is one way to solve your problem -- triggers are another. But as a general rule I don't believe you should rely on automated deletes in the database. I think it is better to use a stored procedure to manage this delete by finding all dependencies and remove them first, and then going ahead with the delete from the primary key table. This way, you know exactly what's going on in your database.
I'm surprised that you continued to get a FK error after modifying the FK with cascading delete. Maybe post the exact error and your updates to the table and we can have a better grip on what's happening?

Check for duplicate column values (not a key) in SQL

Is there a way for SQL to enforce unique column values, that are not a primary key to another table?
For instance, say I have TblDog which has the fields:
DogId - Primary Key
DogTag - Integer
DogNumber - varchar
The DogTag and DogNumber fields must be unique, but are not linked to any sort of table.
The only way I can think of involves pulling any records that match the DogTag and pulling any records that match the DogNumber before creating or editing (excluding the current record being updated.) This is two calls to the database before even creating/editing the record.
My question is: is there a way to set SQL to enforce these values to be unique, without setting them as a key, or in Entity Frameworks (without excessive calls to the DB)?
I understand that I could group the two calls in one, but I need to be able to inform the user exactly which field has been duplicated (or both).
Edit: The database is SQL Server 2008 R2.
As MilkywayJoe suggests, use unique key constraints in the SQL database. These are checked during inserts + Updates.
ALTER TABLE TblDog ADD CONSTRAINT U_DogTag UNIQUE(DogTag)
AND
ALTER TABLE TblDog ADD CONSTRAINT U_DogNumber UNIQUE(DogNumber)
I'd suggest setting unique constraints/indexes to prevent duplicate entries.
ALTER TABLE TblDog ADD CONSTRAINT U_DogTag UNIQUE(DogTag)
CREATE UNIQUE INDEX idxUniqueDog
ON TblDog (DogTag, DogNUmber)
It doesn't appear as though Entity Framework supports it (yet), but was on the cards. Looks like you are going to need to do this directly in the database using Unique Constraints as mentioned in the comments.

SQL Server PK and FK always equal value

I have question, how can i insert a new data into a database that the primary key and foreign key is always equal in value?
ex. i entered my name into Name table and that Name table has PK and FK. every time i insert a new data, the FK was empty. i expect that the value of FK is same as the value of PK even they have different field name.
above is my database relationship. every time i insert new data the EventsID pk(Eventstbl) wont copy to EvnetsID FK(Organizationtbl)
The referential integrity does not work as you described. It better suits functionality of the triggers. The purpose of the PK and foreign key constraint is to prevent insertion of data which is not exist in other table as PK. Therefore, if you want to copy data from Eventstbl to Organizationtbl upon inserting a new record to the former, you need to write a trigger for the insertion event of the Eventstbl. Your PK - FK constraint will work like following, when you insert new record to Organizationtbl, it will check Eventstbl table for the corresponding EventsID. If it does not exist, it will not allow you to insert new record to Organizationtbl. I hope it helps.
Well, you can use a trigger in EventsTbl, an after insert / update trigger. So this trigger could insert / update the other table you need. You can use the INSERTED table to catch the new value of the PK. I hope it helps.

Why does MS Access 2007 not allow a row insert, but then allow it on the next insert attempt?

My insert statement is:
INSERT INTO myTable (inst_id,user_id,app_id,type,accessed_on)
VALUES (3264,2580,'MyApp','Renew',Now);
...where all of the values are formatted correctly. The table has the above fields and one other, a long int auto-increment key field. The foreign keys are 'inst_id', 'user_id', and 'app_id'.
I am getting this error from Access:
...and the following error from VS 2005 when it errors out:
System.Data.OleDb.OleDbException: The changes you requested to the table
were not successful because they would
create duplicate values in the index,
primary key, or relationship. Change
the data in the field or fields that
contain duplicate data, remove the
index, or redefine the index to permit
duplicate entries and try again.
When making this insert query I can look into the database and see that the each of the foreign key values exist in their respective tables and have been for months (for the particular example I am using). These fields are also set so that I can have duplicates, so that is not the issue. Calls of this nature in other tables works great. I do not need to supply the auto-increment key value in the insert query, it adds it for me automatically (like it should).
The weird thing is that if I do this in my code:
try
{
//Execute the query here...
}
catch
{
//Execute the same query again
}
...or if I just try and execute this within Access twice, it works.
Has anyone encountered this before? Again, this type of insert works for other tables, all foreign keys are present in their respective tables, the primary key of this table is set as 'Auto-increment', and all fields (other than the primary key field of course) are set to allow duplicates.
Any ideas?
EDIT: Largest key before inserting: 343085. Largest key after inserting: 343086. The format is:
id: AutoNumber (Field Size=Long Interger, New Values=Increment, Indexed=Yes - No Duplicates)
inst_id: Number (Field Size=Long Interger, Required=Yes, Indexed=Yes - Duplicates OK)
user_id: Number (Field Size=Long Interger, Required=Yes, Indexed=Yes - Duplicates OK)
app_id: Text (Field Size=255, Required=Yes, Indexed=Yes - Duplicates OK)
type: Text (Field Size=50, Required=Yes, Indexed=No)
accessed_on: Date/Time (Default Value=Now(), Required=Yes, Indexed=No)
Going by some old memory here...
Try putting a timestamp field in your table.
I can't remember exactly why that works -- something to do with Access having difficulty identifying records / maybe some kind of locking or indexing quirk. I did some research on that several years ago when it happened to one of my tables.
The key violation the error refers to isn't a missing key in another table, it's a duplicate key in the same table. Sometimes, Access gets it's wires crossed and thinks that the key it's assigning to the new record is already assigned to another record in the table. I don't know what causes that to happen. But by putting a timestamp field in the table, it causes Access to think differently.
It's a frustrating fix, because I don't know why it works. And now I have an otherwise useless timestamp field in my table. But so be it.
MS-Access has been known to barf up spurious errors that have nothing to do with the problem they report. It wouldn't hurt to surround the column called "type" with brackets, [type].
http://office.microsoft.com/en-us/access-help/access-2007-reserved-words-and-symbols-HA010030643.aspx#_Toc272229038
Is the value Now changing between attempts so that there is now no longer a duplicate key error?
INSERT INTO myTable (inst_id,user_id,app_id,type,accessed_on)
VALUES (3264,2580,'MyApp','Renew',Now);
Can you just check this out with accessed_on datatype and Now datatype
Change the value type of DateTime to String while inserting that will be good.
Do let me know if this works for you.
Thanks
rAfee
I believe Jet/ACE will not understand the NOW() method.
And i worked with ACE version, the syntax could not work.
Need to find the other way for direct implementing the syntax.
I know long time ago I had a similuar issue. In my cases I was getting the same error but I didn't have any unique indexes in the table. I finally solved it by reparing and compacting the database.

Categories