I have this insert trigger which handles duplicate key insert attempts:
-- Create trigger to not throw in case of duplicate mapping attempt
CREATE TRIGGER dbo.BlockDuplicates_Product_Category_Mapping
ON dbo.Product_Category_Mapping
INSTEAD OF INSERT
AS
BEGIN
SET NOCOUNT ON;
IF NOT EXISTS (SELECT 1
FROM inserted AS i
INNER JOIN dbo.Product_Category_Mapping AS p
ON i.ProductId = p.ProductId
AND i.CategoryId = p.CategoryId)
BEGIN
INSERT INTO dbo.Product_Category_Mapping (ProductId, CategoryId, IsFeaturedProduct, DisplayOrder)
SELECT ProductId, CategoryId, IsFeaturedProduct, DisplayOrder
FROM inserted;
END
ELSE
BEGIN
PRINT 'Duplicate';
END
END
And it works fine if I run it directly from my DBMS:
But, if I use it in code with EF:
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.15" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="3.1.15" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.15" />
It doesn't seem to work, a duplicate key exception is thrown, which is what I was trying to avoid:
Microsoft.EntityFrameworkCore.Relational: An error occurred while updating the entries. See the inner exception for details. Core Microsoft SqlClient Data Provider: Violation of UNIQUE KEY constraint 'UQ_PCM_ProductId_CategoryId'. Cannot insert duplicate key in object 'dbo.Product_Category_Mapping'. The duplicate key value is (920, 129).
This is being inserted through a navigation property, if it makes any difference.
Can someone point out to me why this is not working?
I followed these two related questions but I don't see nothing that can help:
UNIQUE CONSTRAINT
? This smells like an XY problem.