Tags

, ,

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

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]

attributes for the purpose, for example :

namespace CustomerBase.Models
{
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    public partial class Customer
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }

        [Required]
        [StringLength(100)]
        public string EmailAddress { get; set; }

        [Required]
        [StringLength(50)]
        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

 

Pitfall
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.

Advertisements