简体   繁体   中英

Handling return values on EntityFramework stored procedure mapping

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

This usually happens when primary keys of context don't match with the database. You can update your model and try again.

You must map the ID returned by your stored procedure to the ID of your entity in Entity Framework. You do so by adding a result column binding in the stored procedure mapping window.

Otherwise, the ObjectContext does not know the ID for the object has changed, and will keep it as 0. When EF then tries to insert the second record it succeeds, but it finds itself with two records with the same primary key (0).

This is why it says The changes to the database were committed successfully, but an error occurred while updating the object context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM