Using the Entity Framework stored procedure mapping I am inserting records into a table. Before the insert I will do some validation based on that I will insert the record and return the id.
When validation fails I will return 0 because of that EF throws the following error:
The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state.
Inner exception message: AcceptChanges cannot continue because the object's key values conflict with another object in the ObjectStateManager. Make sure that the key values are unique before calling AcceptChanges.
Stored procedure code:
alter PROCEDURE [dbo].[testpro]
@field1 VARCHAR(20),
@field2 varchar(20)
AS
DECLARE @field3 INT;
DECLARE @id INT=0;
BEGIN TRANSACTION
SAVE TRANSACTION STARTWORK
SELECT @field3 = ID
FROM anothertable
WHERE field = @field1
IF @field3 <>0
BEGIN
--INSERT(@field,@field2,@field3)
SET @ID = SCOPE_IDENTITY()
END
COMMIT TRANSACTION
SELECT @ID AS ID
GO
Entity Framework code:
records.ForEach((record) =>
{
repository.Add(record);
});
repository.UnitOfWork.Save();
I know the reason for error, but how to handle this issue ?
I am using EF 5
Note: Above code works if IF condition get passed, it throws error only when I'd value is not populated