2

My entity is like that:

public class Foo
{
     public int Id { get; set; }
     public int Bar { get; set; }
}

Bar has a unique index.

In my code I get two Foo objects:

object 1: { Id: 1, Bar: 1}
object 2: { Id: 2, Bar: 2}

What I need to do is to swap one by other:

object 1: { Id: 1, Bar: 2}
object 2: { Id: 2, Bar: 1}

and update this in a transaction. But when I do this, I get an error similar to that:

Cannot insert duplicate key row in object 'dbo.Episode' with unique index 'IX_Id_Season_Number'. The duplicate key value is (2f649a95-0a03-e511-9751-0090f5a7af27, 3, 1).
The statement has been terminated.

How can I do that?

Kian Cross
  • 1,818
  • 2
  • 21
  • 41
MuriloKunze
  • 15,195
  • 17
  • 54
  • 82

1 Answers1

2

You will need to have an additional update for one of the objects where Bar is set to some dummy value that meets your constraint, since constraints are evaluated per update and not per transaction. Here's some pseudocode:

object 1: { Id: 1, Bar: 2}  
object 2: { Id: 2, Bar: -1} // or some other dummy value
save
object 2: { Id: 2, Bar: 1}
save

Since you're putting everything within a transaction, you won't have to worry about the database ending up in the intermediate state if something goes wrong.

See

Community
  • 1
  • 1
jjj
  • 4,822
  • 1
  • 16
  • 39