How to set Identity Column attribute for property in Entity Framework

This is one of the questions that I get a lot from developers who are using code first approach for Entity Framework. "How to specify a class property to be Identity column in database?" If you look at various data annotation attributes that are available for class properties you do not find any that is named like Identity. This does not mean that entity framework does not allow mapping a class property to a field that is marked as Identity in database. After digging through these annotations, I found DatabaseGenerated attribute that allows you to set Identity column. The constructor of this attribute forces you to set atabaseGeneratedOption option. This enumeration has three values.

None
Identity
Computed

The following code snippet shows how this attribute can be set on a class.

public class ProductStatus
 {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
        public int ProductId { get; set; }
        public Status Status { get; set; }
 }

Search

Social

Weather

9.0 °C / 48.3 °F

weather conditions Clear

Monthly Posts

Blog Tags