2

In T-SQL, to resolve the insert/update racing condition, one uses WITH (UPDLOCK, SERIALIZABLE). Example: two session threads trying to insert on the same primary key:

Example:

IF EXISTS(SELECT * 
          FROM dbo.Foo WITH (UPDLOCK, HOLDLOCK) 
          WHERE ID = @ID)

How does one apply this in the latest version of C# ASP Entity Framework 6 EF6 for the OLTP environment? What are the keywords to utilize in EF6?

Instead of using Inline SQL above, I would rather refer to the C# class objects.

Thanks,

ChrisF
  • 134,786
  • 31
  • 255
  • 325
  • https://stackoverflow.com/q/27002474/861716 – Gert Arnold Oct 27 '17 at 07:40
  • that was in 2014, hopefully entity framework 6 has this mechanism –  Oct 27 '17 at 14:27
  • Nope, and it won't ever. – Gert Arnold Oct 27 '17 at 14:31
  • thats strange, that thought was point of object relational mapper, to get away from using sql data, and using C# objects, thanks anyway –  Oct 27 '17 at 14:32
  • It sure is, and that's why an ORM tries to keep the nitty-gritty details of locking and transactions away from the user. In other words: they pursue *persistance ignorance*. An ORM will do for 95% of regular user-database interactions in OLTP systems. Using more advanced features of the underlying data store will always require specialized interfaces (like TransactionScope or ADO.Net). – Gert Arnold Oct 27 '17 at 14:39

1 Answers1

1

In general EF uses client-side optimistic concurrency controls. In this case, that means that you have a primary key or unique index on the key you are using to check for existence, and treat key violation error the same as finding an existing entity in the initial check.

If you expect duplicates to be rare, you can also opt to omit the initial check and simply rely on the key violation error.

David

David Browne - Microsoft
  • 80,331
  • 6
  • 39
  • 67