Anjan Kumar
Anjan Kumar

Reputation: 21

EF Auto-increment a non primary column with a seed value

I have a Order table and it has OrderNumber column of type INT. Order table also has a Id column which is Primary key. I need to make OrderNumber column to autoincrement the values from a Seed value. Any help?

Thanks Anjan

Upvotes: 2

Views: 2133

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236308

You can assign auto-increment to any column, but I would not do that, because OrderNumber is definitely identity of your Order entity. You should use it as primary key:

[Key] // make it primary key and remove Id property
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int OrderNumber { get; set; }

Adding auto-increment with fluent api looks like:

modelBuilder.Entity<Order>()
   .Property(o => o.OrderNumber)
   .HasDatabaseGenerationOption(DatabaseGenerationOption.Identity);

If you want to create seed for OrderNumber then you should use custom database initializer and execute DBCC CHECKIDENT query

DBCC CHECKIDENT ('Orders', RESEED, YourSeedValue)

Upvotes: 1

Related Questions