Why does SqlException over FK violation doesnt present the violated value? - c#

I am bulk inserting a long list of object.
than i execute a commit.
It fails sometimes with the error (C#)
"The INSERT statement conflicted with the FOREIGN KEY constraint
"FK_MyFK". The conflict occurred in database "DCDCommunity", table
"MySchema.MyTable", column 'Id'.\r\nThe statement has been terminated."}
System.Exception {System.Data.SqlClient.SqlException}
Now, do I have to write a program that iterates on my data files to find the value or can I get it in the exception?

I can't answer "why?" but I can offer a suggestion - do some pre-checks to your data before doing a bulk insert to make sure foreign keys are valid, and whatever other data issues you might regularly face - like checking string lengths to avoid the "string or binary data would be truncated" error as mentioned in a comment.

Related

Determine record exist by exception of SQL is Principles?

I have a table with primary key and I want to insert new record to that.
In my code, I check if record exists by exception. In the SQL stored procedure, I have insert code and surround by exception, in my application I execute that stored procedure and want to insert new record, if my record exist in table, insert code throws an error:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Sup_Item_Sup_Item_Cat". The conflict occurred in database test, table test. The statement has been terminated.
and goes to the catch block.
In my application I check the error that was returned by SQL, and it shows a message box to user that record is exist.
I want to know, is this way is Principles? or I must use if exist statement in SQL?
Exception should never be used when you can avoid it and return a value.
Exception is a "stress" on a system and much slower than any other way.
Its customary for a SP to return 0 if everything is Ok and a negative value if there is an error.
Either check your SP return code in application or use out parameter to determine problem. An error should be truly an error.

"Violation of PRIMARY KEY constraint” when Inserting in database

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.

How to ignore LINQ to SQL on unique key?

I insert data with LINQ to SQL on my DB on a table where there is a unique key on 2 columns.
When I try to insert a row with this unique key already inserted, I get:
Cannot insert duplicate key row in object 'dbo.613_LiveLove' with
unique index 'IX_613_LiveLove'. The duplicate key value is
(35715346455553, paul). The statement has been terminated.
I don't want this error message, just "LINQ to SQL, does not insert it" and continue the process.
Is there a way on doing this? Or need I to use try/catch?
This might help: http://msdn.microsoft.com/en-us/library/bb425822.aspx#linqtosql_topic18
"... any errors detected by the database will cause the submission process to abort and an exception will be raised. All changes to the database will be rolled back as if none of the submissions ever took place. The DataContext will still have a full recording of all changes so it is possible to attempt to rectify the problem and resubmit them by calling SubmitChanges() again..."
Use try catch. Catch the specific exception type, and throw your own exception (you propably want to create your own exception type) including your custom message. At the location in you code you want to continue the process, just catch that exception.

The INSERT statement conflicted

My project in C# Winforms 2010 and use SQL Server express and Linq-to-SQL. My project get me exception:
The INSERT statement conflicted with the CHECK constraint "CK_BarCode_Num". The conflict occurred in database "Parking", table "dbo.TBL_Cards", column 'BarCode_Num'
and when I ran this query:
SELECT name, definition
FROM sys.check_constraints
WHERE name = 'CK_BarCode_Num'"
the output shows the definition of:
Name: CK_BarCode_Num
Definition: (datalength([BarCode_Num])=(13))"
but in TBL_Cards in database, type of BarCode_Num is varchar(100) and in code behind, I declare int for type of BarCode_Num.
I don't know where is set datalength([BarCode_Num])=(13)?
The check constraint is saying that whatever you insert into Barcode_Num has to be exactly 13 characters long.
If you're trying to insert something that isn't 13 characters long, I'd recommend you consult the documentation for your database (or talk to whoever set it up) to understand why this constraint has been applied.
We'll not be able to answer that for you, and I wouldn't recommend altering the check constraint without understanding why it exists in the first place.
DATALENGTH
Returns the number of bytes used to represent any expression.
For varchar, the number of bytes used corresponds 1-1 with the number of characters. For nvarchar you would need to divide by 2.
The data type is separate from any check constraints you have defined. You can modify the check constraint following these instructions: http://msdn.microsoft.com/en-us/library/ms191273.aspx
Otherwise, you can perform the data validation in your own code - Linq to SQL won't enforce it on the entity, but will throw a SqlException when you attempt to perform an insert that violates the constraint.

getting {"could not execute batch command.[SQL: SQL not available]"} error from NHibernate

I took a look at other related posts but couldn't find any solution.
Sometimes on sesstion.Flush() I get the following error:
{"could not execute batch command.[SQL: SQL not available]"}
and the Inner Exception :
{"The UPDATE statement conflicted with the FOREIGN KEY constraint FK1377052553ABF955. The conflict occurred in database ProcessDebug, table dbo.Adjustment, column 'AdjustmentId'.The statement has been terminated."}
a piece of Process class mapping :
References(p => p.CurrentAdjustment)
;
References(p => p.DefaultAdjustment)
;
HasMany(p => p.Adjustments)
.Cascade.AllDeleteOrphan()
.Inverse()
;
All these properties above are of type of Adjustment.
As long as I get this error once in a while I couldn't track it down. For an entity it might happen now, but not next time in a same piece of code....
Any idea what might cause the problem?
I'm using NH 3.2 and FluentNhibernate
Thanks in advance
In my situation, it was "NULL" in one of the databese columns. Check your database data.
FOREIGN KEY -> this means, that you propably have null i column, that is use for "join".
p.s. Take SQL Profiler and check the SQL generated by nHibernate.
You need to look at the sql that is actually trying to execute.
It appears as though you are trying to update the primary key ("AdjustmentId") to something that does not exist. Hence the foreign key violation.
it seems about you database, not your nHibernate codes, check the SQL in log file, and try to exec it
To find the actual cause, you'll need to see the SQL that is being generated by nHibernate. You can either use nHibernate log or nHibernate profiler to get these SQL. Few of the common issues related to the above error message, include:
String or binary data would be truncated. An example of this issue is whenever you provide a string value that is larger than the defined varchar/nvarchar field size in database.
Expected primary or foreign key value is null
may be its not NHibernate problem!
please check in database which column is Not Null/Null. For this,I set null those columns.
You can do anything! set value when insert or set null on those column on table.
In my case I'm adding a data with column whose type is DateTime,
I insert 2100/2/2 get this error, but when insert more reasonable time 2001/2/2 get success,
so maybe the problem is in your data, and should follow some rule in database.

Categories