EF : Code First – Auto Increment Key

No need for an explanation for the subject. Its a general scenario to have an auto incremental key column in DB. So, we can use


attributes for the purpose, for example :

namespace CustomerBase.Models
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    public partial class Customer
        public int Id { get; set; }

        public string EmailAddress { get; set; }

        public string LastActivityTime { get; set; }

so, when we insert a new record, we can just have :

CustomerBaseContext customerBaseDb = new CustomerBaseContext(); //The DB Context
customerBaseDb.Customers.Add(new Customer
        EmailAddress = "john@doe.com", 
        LastActivityTime = DateTime.Now.ToString()
    }); //No need to explicitly tell ID
customerBaseDb.SaveChanges(); //Commit transaction


If you forget to mention [Key] , assuming you have made it not null, and explicitly say Id in C# code, EF will try to pass NULL since its an identity and will throw an exception “Cannot insert the value NULL into column……….“, so can just modify DatabaseGeneratedOption.Identity to DatabaseGeneratedOption.None – which might not fulfill the auto-increment need. So, just keep [Key] and let DB generator to fill it for you. This is the approach when it comes to concurrency.


Happy Coding.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s