I am building an API with OrmLite from ServiceStack.
When populating it with test data I get the following error:
The INSERT statement conflicted with the FOREIGN KEY constraint
"FK_Order_Customer_CustomerId". The conflict occurred in database
"C:\USERS\ALECTAYLOR\SOCIALBOOTSTRAPAPI\SRC\SOCIALBOOTSTRAPAPI\APP_DATA\USERAUTH.MDF",
table "dbo.Customer", column 'Id'. The statement has been terminated.
Code (lines 213-236 + CreateOrders function): http://pastebin.com/Njhz7sD2
Profiler output: http://fiddle.jshell.net/cTen2/1/show/
Thanks for any advice on how to rectify this issue.
FOREIGN KEY constraint generally means that you are trying to insert a value into a table that doesn't exist in the reference table. Take a look at MSDN article on Foreign Keys for more info about what they are and how they work. You need to have a look at the actual structure of the data tables order and customer.
I would guess that you are inserting a customerId into the orders table that doesn't exist in the customers table.
since this is the insert that's failing, the only logical explanation is that customer number 1 doesn't exist. I saw that you insert 3 customers a few lines before. Maybe the transaction was not committed between the moment the customers were inserted and the order is inserted.
INSERT INTO "Order" ("CustomerId", "ShopId", "ShippingAddress",
"OrderDate", "RequiredDate", "ShippedDate", "Total") VALUES (1, 0,
'{line1:440 Crescent St, line2:South Melbourne, postCode:7416,
city:Melbourne, country:Australia}', '20120430 07:43:18.686', NULL,
NULL, 0);
Try to commit the insert after you insert the clients and before you insert the orders
Alright, got it to work.
Needed to set the ShopId of Order and orderId of the orderDetails List.
http://pastebin.com/TbrW150T
Related
Im working on database design on Microsoft Sql server management Studio, I have a small problem. A LibraryItem should have a required category tied with a foreign key of CategoryId mapped to Id in the table Category as shown in the picture.
SEE THE IMAGE
SECOND IMAGE
I need help with how I can tie CategoryId(FK) to Id(PK on Category Table). I just dont know how to do it excatly.
You'll need to add the reference to the script that creates the table and add a name to the constraint like so:
CONSTRAINT FK_LibraryItem_Category_CategoryId FOREIGN KEY ([CategoryId]) REFERENCES [dbo].[Category] ([Id])
Note: I've defaulted to the dbo schema. You will need to change that if it's different for the Category table you are creating.
That will create a Foreign Key for your LibraryItem table and link the CategoryId to the respective record in the Category table.
Another thing to note as well: This will throw errors if your value for the FK doesn't match an ID in the Category table.
To ellaborate on the errors:
Let's say you add a CategoryId of 2 to a record in your LibraryItem table but a record with the ID of 2 doesn't exist in your Category table, it will throw an error similar to this:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_LibraryItem_Category_CategoryId". The conflict occurred in database "foo", table "dbo.LibraryItem". The statement has been terminated.
This can be easily solved by ensuring the IDs match in both tables.
Now I have read many threads addressing this issue but my issue is:
I'm trying to save multiple Customers in a loop> The First Customer is getting Saved but the next customer it fails. Now I tried this with multiple Set of Customers every time when it tries to save a customer Excluding the First Customer I'm getting the following error message:
Exception Details: System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_COPS.Address_GraphiteGTCCore.YesNoQuestion_IsPrimaryId". The conflict occurred in database "COPSDB", table "GraphiteGTCCore.YesNoQuestion", column 'Id'. The statement has been terminated.
I'm Using a Microsoft Microsoft SQl Server 2012
The IsPrimary which is mentioned in the error Message is YesNoQuestion which is an Enumeration.
A Customer table contains Address which has a Property called "IsPrimary" it is a Required Field also I'm assigning the Value as Yes. I found this Create Behaviour is Used in multiple places and it looks like it works fine everywhere
I tried it from different accounts and tried different assigning I know it is not much but this weird I cannot do much after that.
Ran a trace and got an exception in following query:
exec sp_executesql N'INSERT [COPS].[Address]([Name], [IsResidentialId], [StatusId], [IsPrimaryId], [CountryId], [TypeId], [EventRegistrationId], [ObjectId])
VALUES (#0, NULL, #1, #2, #3, #4, #5, #6)
SELECT [Id], [TimeStamp]
FROM [COPS].[Address]
WHERE ##ROWCOUNT > 0 AND [Id] = scope_identity()',N'#0 nvarchar(max) ,#1 int,#2 int,#3 int,#4 int,#5 int,#6 nvarchar(40)',#0=N'DAVID STARR',#1=1,#2=0,#3=17,#4=1,#5=1138,#6=N'e0386866-51ea-438c-98f0-b172f325705e'
I sounds to me as if you are trying to save a row in the database and either not providing a foreign key that is required, or an invalid foreign key for the customer. It is a bit hard to answer without more information, like an overview of the tables involved, and maybe some code :-)
I'm trying to insert order details into my DB, and it keeps saying:
Cannot insert explicit value for identity column in table 'Orders' when IDENTITY_INSERT is set to OFF.
All I am trying to do is simply insert the users UserId into the UserId column, by using WebSecurity.CurrentUserId - Why is this not working?
I have:
dbase.Execute("INSERT INTO Orders
(UserId, OrderId, Status)
VALUES
(#0, #1, #2)",
WebSecurity.CurrentUserId,
Session["OSFOID"],
"Confirmed");`
So, as you can see, it's pretty simple. But, why won't it work?
My table definition is:
Unless you enable the ability to do identity-insert (by setting identity-insert on for that table), you are NOT ALLOWED to touch that column - the database owns it.
Either enable identity insert briefly, or: don't try to insert the UserId (let the DB create a new id).
As per books online, SET IDENTITY_INSERT:
SET IDENTITY_INSERT Orders ON
INSERT INTO Orders (UserId, OrderId, Status) VALUES (#0, #1, #2)
SET IDENTITY_INSERT Orders OFF
More likely, though: if this is the Orders table, should the identity not be on OrderId ? You'd still have the same problem since you are trying to control the OrderId, of course.
Generally you would not want to insert an integer into a primary key column. You would usually set the column's "Identity" flag to true only where you wanted to have SQL Server set an auto-incrementing integer into this column on insert.
As with Marc Gravell's answer, you can enable identity insert using
SET IDENTITY_INSERT [ database. [ owner. ] ] { table } { ON | OFF }
But doing this in regular application code is really unhealthy -- you'll end up with concurrency issues and quite likely duplicate identities. Better, don't insert the Order's ID -- let the DB do it for you automatically, and then simply query for the new ID using ##IDENTITY (or better, SCOPE_IDENTITY()).
If for some reason you definitely need to store the user's session id, make this a separate column on the order table, or better still, on a separate User table, with the UserId being a foreign key.
You do not want the UserID to be an Identity, and I also do not think you want the UserID to be the primary key either. More than likely, you want the OrderID to be the primary key, or at best shared primary key with the userid and orderid.
In your table's definition set Is Identity? as False, with out setting that you cant insert a value manually to the UserID
You have set IS Identity to YES that's why now you cant insert value for this column DB will automatically insert it by incrementing values..
And the thing i am seeing you set UserId as the primary key of the table which is wrong Order OoderID should be the primary key of the column.
Set UserID IsIdentify to false
and OrderID IsEdentitfy to yes and made it primary key column.
Interestingly I found that when I created a table using a "Select.....Into [new table] from [tables containing data]" I subsequently could not Insert new records, getting the Insert_Identity set to off message.
I got around this by deleting the table then using a Create Table script to rebuild it and now have no problems inserting as many new IDs as needed
I am working with PostgreSql DB using Entity Framework:
When I add new item into DB it generates strange code:
INSERT INTO (SELECT "person_contact"."person_id" AS "person_id",
"person_contact"."contact_id" AS "contact_id"
FROM "public"."person_contact" AS "person_contact")
("person_id","contact_id")
VALUES (cast(141792 as int8),cast(289406040 as int8))
So it add
SELECT "person_contact"."person_id" AS "person_id",
"person_contact"."contact_id" AS "contact_id"
FROM "public"."person_contact" AS "person_contact"
instead of table name "public"."person_contact"
How to resolve this Entity Framework bug ???
UPD: Same issue when I try to delete "person_contact" entry. In delete statement instead of table name - select query.
There are several ways to try and fix this:
Firstly, it could be that your model has become corrupt. You could try deleting the model and recreating it. Also see my answer to this question: SQL Server foreign keys messing with entity framework model
Secondly, you say that it only happens with this table. Is there anything special about this table.
Thirdly, you could try a different .net connector for ProgressSQL, see: http://www.devart.com/dotconnect/entityframework.html
These are listed in the order that I would try them.
Most likely you forgot to create primary key on this table.
I've had the same problem and the solution in my case was very simple. The problem was that I had a column named "id", but I forgot to make it Primary Key. The moment I set it as Primary Key everything was OK.
It is very strange, because EF, normaly won't import table without primary key, but when you have column named "id" it assumes that it is a primary key.
The structure of my table was:
*DROP TABLE IF EXISTS "public"."fact_season_tickets";
CREATE TABLE "public"."fact_season_tickets" (
"id" int8 DEFAULT nextval('fact_season_tickets_id_seq'::regclass) NOT NULL,
"season_ticket_id" int8 NOT NULL,
"date_key" int4 NOT NULL,
"station_id" int4 NOT NULL,
"amount" numeric(18,2) DEFAULT 0 NOT NULL,
"status" int4 NOT NULL
)
WITH (OIDS=FALSE)*
The generated by NpgSql INSERT statement was:
*INSERT INTO (SELECT "fact_season_tickets"."id",
"fact_season_tickets"."season_ticket_id",+
"fact_season_tickets"."date_key",
"fact_season_tickets"."station_id",
"fact_season_tickets"."amount",
"fact_season_tickets"."status"
FROM "public"."fact_season_tickets" AS "fact_season_tickets")
("season_ticket_id","date_key","station_id","amount","status")
VALUES (510::int8,20150630,2,18.00::numeric,1)
RETURNING "id"*
The solution was just creating a primary key:
*ALTER TABLE "public"."fact_season_tickets" ADD PRIMARY KEY ("id");*
I'm trying (SQL Server Compact) to add primary key constraint on existing table that has some rows in it. While adding primary key I'm getting the error:
"A duplicate key cannot be inserted into a unique index"
I don't what this is, can anyone help me with this?
Make sure the data in the table respects the contraint you're trying to set on the table. If the column you are making primary has duplicate entries, it won't be able to work as primary key, hence the error.
You could try and find the rows with duplicate entries, with something like this:
select Id, Count(*) from myTable
having Count(*) > 1
group by Id
Try this
select id_column, count(*) from your_table group by id_column having count(*) > 1
If there are any records returned from this above query you cannot add a primary key on id_column since duplicate IDs exist.
Of course you will need to replace id_column and your_table with the appropriate names.