One of my small database management projects (written in delphi) used sql queries to find the first free id of mysql table.

Example: I have to find the first free id (hole) in a table like this:

<!-- language: lang-none -->
| id   | Col1 |
|------|------|
| 5101 | ABC  |
| 5102 | BCD  |
| 5103 | CDE  |
| 5105 | EFG  | 🡔 first missing id
| 5106 | GHI  |
| 5108 | ILM  |

The code should find the first free id 5104

Here's how I'd do it in SQL (in old project):

<!-- language: lang-sql -->
SELECT
  MIN((doc.id + 1)) AS nextID
FROM (doc
  LEFT JOIN doc doc1
    ON (((doc.id + 1) = doc1.id)))
WHERE (ISNULL(doc1.id) AND (doc.id > 5000))

Now, which I am rewriting in c # language, I need to convert sql statements into a LINQ query (which uses Devart dotConnect for mysql Entity Framework). Starting from here:

DC db = new DC();
var nums = db.Documentos.OrderBy(x => x.Id);

From Can LINQ be used to find gaps in a sorted list?:

var strings = new string[] { "7", "13", "8", "12", "10", "11", "14" };
var list = strings.OrderBy(s => int.Parse(s));
var result = Enumerable.Range(list.Min(), list.Count).Except(list).First(); // 9

Basically, order the list. Then create an array of sequential numbers (1,2,3...) from the minimum all the way to the max. Check for missing values in the list, and grab the first one. That's the first missing number.