INSERT statement conflicted with the FOREIGN KEY constraint
LINQPad v9.6.6
LINQ-to-SQL database connection
Given a set of tables defined as
CREATE TABLE dbo.tbl_qa_Equipment (
EquipmentID INT IDENTITY(1,1) PRIMARY KEY,
EquipmentType CHAR(2) NOT NULL,
-- Identifiers
AssetNum VARCHAR(50) NULL,
SerialNum VARCHAR(200) NULL,
ManufacturerID INT NOT NULL,
ModelNum VARCHAR(100) NULL,
Description VARCHAR(200) NULL,
IsExternalAsset BIT NOT NULL DEFAULT 0,
SiteID VARCHAR(10) NULL,
-- Audit
CreatedDate DATETIME NOT NULL DEFAULT GETDATE(),
IsActive BIT NOT NULL DEFAULT 1,
CONSTRAINT CK_Equipment_Type CHECK (EquipmentType IN ('FG', 'TT', 'TW')),
CONSTRAINT FK_EquipmentExt_MI FOREIGN KEY (ManufacturerID)
REFERENCES dbo.tbl_qa_Manufacturer (ManufacturerID)
);
GO
CREATE INDEX IX_Equipment_AssetNum ON dbo.tbl_qa_Equipment (AssetNum)
WHERE AssetNum IS NOT NULL;
CREATE INDEX IX_Equipment_SerialNum ON dbo.tbl_qa_Equipment (SerialNum)
WHERE SerialNum IS NOT NULL;
CREATE INDEX IX_Equipment_Type ON dbo.tbl_qa_Equipment (EquipmentType);
GO
-- Force Gauge Equipment Extension
CREATE TABLE dbo.tbl_qa_fg_EquipmentExt (
EquipmentID INT NOT NULL PRIMARY KEY,
MaxCapacity DECIMAL(10,2) NOT NULL,
UnitOfMeasureID INT NULL,
CONSTRAINT FK_fg_EquipmentExt_Equipment FOREIGN KEY (EquipmentID)
REFERENCES dbo.tbl_qa_Equipment (EquipmentID),
CONSTRAINT FK_fg_EquipmentExt_UOM FOREIGN KEY (UnitOfMeasureID)
REFERENCES dbo.tbl_qa_fg_UnitOfMeasure (UnitID)
);
with code like
// Insert tbl_qa_Equipment
var newEquip = new Tbl_qa_Equipment
{
EquipmentType = "FG",
AssetNum = eq.EquipNum,
SerialNum = eq.SerialNum,
ManufacturerID = eq.ManufacturerID,
ModelNum = eq.ModelNum,
Description = eq.Description,
IsExternalAsset = false,
SiteID = eq.SiteID,
IsActive = true,
CreatedDate = DateTime.Now,
Tbl_qa_fg_EquipmentExt = new Tbl_qa_fg_EquipmentExt()
{
MaxCapacity = (decimal)eq.MaxCapacity!,
UnitOfMeasureID = eq.UnitOfMeasureID
}
};
Tbl_qa_Equipments.InsertOnSubmit(newEquip);
SubmitChanges();
When I hit line SubmitChanges, I'm getting an exception:
SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_fg_EquipmentExt_Equipment". The conflict occurred in table "dbo.tbl_qa_Equipment", column 'EquipmentID'.
Based on my research, the LINQ-to-SQL driver is supposed to do the right thing here of inserting to the primary table and then insert to the secondary table with the insert id from the primary table as the primary key in the secondary table. Is this not the case for a co-PK/FK relationship?
Best Answer
-
Have you tried setting the relationship on the other side?
var parent2 = new Parent { Name = "Test Child-Side Nav" }; var child2 = new Child { Value = 2.22m, Parent = parent2 // FK-side navigation property }; Childs.InsertOnSubmit (child2); SubmitChanges();
Answers
-
Wow. Totally counter-intuitive to my brain. But it worked. Thanks Joe!
