Add GUID as primary key column in code-first migration


Story by Abhilash on Entity Framework

Share   

Last week, I was migrating an old ASP.NET MVC project and as part of that I decided to replace the identity column from auto-incremented numeric value to GUID values which looks more professional.

Below are the changes that you need to make to achieve this.

// in your model class.
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }

 

Run, Add-Migration command which generates your migration class and make below change:

// in your migration class.
AlterColumn("dbo.LoLChampionPickeds", "Id", c => c.Guid(nullable: false, identity: true, defaultValueSql: "newsequentialid()"));

That's it. Now do an Update-Database and your Id field will start using GUIDs.

Thanks.

 






comments powered by Disqus

Related Story   →

Fix: HTML5 Video not playing when deployed to azure

A post on how to playback HTML5 video when published to Azure.