Reputation: 295
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?
Upvotes: 0
Views: 2486
Reputation: 205819
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");
Upvotes: 7
Reputation: 53
You tried not to put anything and make the model like this:
public class Model
{
public long? ModelId {get;set;}
public int? Variable {get;set;}
}
And model Builder:
modelBuilder.Entity<Model>(entity =>
{
entity.HasKey(e => new { e.ModelId, e.Variable} )
.HasName("PK_Model");
});
Upvotes: -1