3

I'm using Entity Framework Core with .NET 6.

I have a function that will auto-generate table primary key of other tables as a id summary and does not consider using Identity specification in SQL Server to auto-generate table primary key.

The function's processes are as follows:

  1. Get the max id of table
  2. Update the newest max id to table
  3. Return the primary id

And I'm facing the similar question to this question, if my website is using more than one server and there is serveral users create data at once, error might occur (with the conflict of the same ids that returned by function).

I was using T-SQL to fix this problem in Entity Framework with .NET framework 4.6 in the past, the solution just like this in the same article above.

But I'm wondering if there is any better solution now in EF Core? I have searched for Isolationlevel in ef core document, but it seems unable to deal with this situation.

Does anyone have a better solution for this?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Chester Chu
  • 395
  • 3
  • 11
  • 1
    The *better solution* would be to let the database properly handle this - using an `IDENTITY` or a `SEQUENCE` - doing this with a `SELECT MAX(id)+1` approach in code is **flawed** and will most likely result in duplicates - **DON'T DO IT!** – marc_s Mar 02 '22 at 08:04
  • If you are searching for a more elegant way to lock tables with EF Core than using raw sql, take a look at the package `Thinktecture.EntityFrameworkCore.SqlServer` and the extension method `WithTableHints()` – Jensen Aug 12 '22 at 08:05

0 Answers0