Search code examples
entity-frameworkef-code-firstcode-first

Entity Framework auto incrementing field, that isn't the Id


I know this isn't the most ideal solution, but I need to add an auto incrementing field to one of my EF Code First objects. This column id NOT the Id, which is a guid.

Is there anyway for me to define the auto incrementing field in code, or would creating the column myself and defining in the DB that its auto incrementing work?


Solution

  • You can annotate that property with DatabaseGenerated(DatabaseGeneratedOption.Identity). EF allows only single identity column per table.

    public class Foo
    {
        [Key]
        public Guid Id { get; set; }
    
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public long Bar { get; set; }
    }