Entity Framework Core 2 auto generated columns

c# entity-framework entity-framework-core sql-server

Question

I have this model:

public class Model
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long ModelId {get;set;}
    public int Variable {get;set;}
 }

I want both variables to be auto incremented on add. If I put [Key] or DatabaseGeneratedOption.Identity also on the Variable property, EF Core says that you can't have 2 identity columns.

I have also tried with FluentAPI:

modelBuilder.Entity().Property(variable => variable).ValueGeneratedOnAdd();

but i still get the same error.

How can I have 2 auto incremented values on add?

1
0
10/25/2018 1:56:34 PM

Accepted Answer

SqlServer allows only one identity column per table. But it allows you to define and use as much sequences as you wish:

A sequence generates a sequential numeric values in the database. Sequences are not associated with a specific table.

Following the above EF Core documentation link, you can instruct EF to create sequence and use it for your Variable column like this (as the documentation states, "You can not configure a sequence using Data Annotations"):

modelBuilder.HasSequence<int>("VariableSequence");

modelBuilder.Entity<Model>().Property(e => e.Variable)
    .HasDefaultValueSql("NEXT VALUE FOR VariableSequence");
5
10/25/2018 2:50:40 PM


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