sql-serverentity-frameworkauto-incrementtph

SQL Server TPH (Table Per Hierarchy) auto increment multiple columns base on type


We currently use TPT (Table Per Type) in Entity Framework, this is very slow as we have about 20 tables, when they are queried, Entity Framework creates some massive disguising SQL which is very slow.

Each table has an auto increment integer column, this allows each type to have a number that is incremented per type. This is what the clients wanted. Now that we are wanting to move to the more performant TPH, we need all these table columns moved to the one table.

How can we have the auto increment columns based on the type as in the results below?

e.g.

Current Job Task

| TaskId    | TaskNumber    |
-----------------------------
| 1234      | 1             |
| 2345      | 2             |

Current Work Task

| TaskId    | TaskNumber    |
-----------------------------
| 3244      | 1             |
| 3245      | 2             |

This is the TPH table structure we want, as you can see, we want the task number to increment based on the Type of task.

| TaskId    | Type      | JobTaskNumber    | WorkTaskNumber   |
---------------------------------------------------------------
| 1234      | Job       | 1                | null             |
| 2345      | Job       | 2                | null             |
| 3244      | Work      | null             | 1                |
| 3245      | Work      | null             | 2                |

I am wondering if we use a seeding table, but any solutions greatly appreciated

Many thanks

Andrew


Solution

  • OK so did what I thought would work.

    Not a hugely nice approach as we need about 20 seed tables.Each table has just an identity id defined as a BIGINT in sql server

    When we want to add and get a new incremented id we just call this using dapper to get the result.

    INSERT INTO SeedMyTable DEFAULT VALUES; SELECT CAST(SCOPE_IDENTITY() AS BIGINT)