Generating auto-incremented value based on group of values SQL Server/EF Core

Viewed 18

Is there a way to generate an auto-incremented id over a "group" of values in SQL Server using EF Core?

Here's the example table i want to achieve

  • UserId is an unique id for user
  • Id1 is normal auto-incremented field
  • Id2 should be a field that is autoincremented over UserId + Id1
--------------------------------------------------------------
             UserId                  |    Id1    |    Id2  
--------------------------------------------------------------
071dae72-e14c-4687-94fb-1a18628f7af5 |     1     |     1
071dae72-e14c-4687-94fb-1a18628f7af5 |     2     |     2
071dae72-e14c-4687-94fb-1a18628f7af5 |     3     |     3
071dae72-e14c-4687-94fb-1a18628f7af5 |     4     |     4
071dae72-e14c-4687-94fb-1a18628f7af5 |     5     |     5

9c6d92e2-3539-4d03-b8f2-57a8d327e76e |     6     |     1
9c6d92e2-3539-4d03-b8f2-57a8d327e76e |     7     |     2
9c6d92e2-3539-4d03-b8f2-57a8d327e76e |     8     |     3
9c6d92e2-3539-4d03-b8f2-57a8d327e76e |     9     |     4
9c6d92e2-3539-4d03-b8f2-57a8d327e76e |    10     |     5
--------------------------------------------------------------

CREATE TABLE [Events] (
    [UserId] uniqueidentifier NOT NULL,
    [Id1] bigint NOT NULL IDENTITY,
    [Id2] bigint NOT NULL,
    CONSTRAINT [PK_Events] PRIMARY KEY ([UserId])
);

So far i tried approach with EF default sql, computed values and functions but I can't make it work

public class BaseModel
{
    public Guid UserId { get; init; }
    public int Id1 { get; init; }
    public int Id2 { get; init; }
}

public class DbContext
{
    modelBuilder.Entity<BaseModel>()
        .Property(x => x.Id1 )
        .ValueGeneratedOnAdd();

    modelBuilder.Entity<BaseModel>()
        .Property(x => x.Id2);
}

Is there a way to make it database-side? I can generate it on app-side but I want to avoid this

0 Answers
Related