How to auto increment Id with VARCHAR or NVARCHAR in Entity Framework Core?

asp.net asp.net-core entity-framework entity-framework-6

Question

I used to do that using a compound column in my SQL code before.

[ID] [int] IDENTITY(1,1) NOT NULL,
[PreFix] [varchar](50) NOT NULL,
[EmployeeNo]  AS ([PreFix]+ RIGHT('0000000' + CAST(Id AS VARCHAR(7)), 7)) PERSISTED,
1
1
4/15/2020 6:54:43 AM

Popular Answer

There are mainly different workarounds, the simplest would be modifying the OnModelCreating method to use one of the fluent API functions HasComputedColumnSql on the computed column.

Code First Approach

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Employee>()
    .Property(e => e.EmployeeNo)
    .HasComputedColumnSql("[PreFix]+ RIGHT('0000000' + CAST(Id AS VARCHAR(7)), 7)");
}

Database First Approach

For a database first approach you could still have the computation logic defined while creating the table and use the following modification in the context side of the entity framework core.

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Contact>()
            .Property(p => p.EmployeeNo)
            .ValueGeneratedOnAdd();
    }
2
4/15/2020 11:32:10 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow