Skip to content

Using Guid Column as Primary Key

SteveAndrews edited this page May 7, 2020 · 2 revisions
  • Property type should be System.Guid
    • public Guid UserId { get; set; }
  • AutoIncrement should be set to true
    • [PrimaryKey("UserId", AutoIncrement = true)]
  • You do not need to initialize the property in the constructor
    • //// Not necessary - this.UserId = Guid.NewGuid();

Example

[TableName("Users")]
[PrimaryKey("UserId", AutoIncrement = true)]
public class User
{
    public Guid UserId { get;set; }

    [Column("emailAddress")]
    public string Email { get;set; }

    [ResultColumn]
    public string ExtraInfo { get;set; }

    [Ignore]
    public int Temp { get;set; }
}

Table Design

To create the column in SQL Server, ensure the following settings:

  • Data Type: uniqueidentifier
  • Allow Nulls: false
  • RowGuid: Yes
  • Default Value or Binding: (newid())