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

JamesStuddart picture JamesStuddart · May 3, 2012 · Viewed 41.6k times · Source

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?

Answer

Eranga picture Eranga · May 3, 2012

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; }
}