Raheel Khan Raheel Khan - 1 month ago 11
SQL Question

Use an auto-generated UNIQUEIDENTIFIER that is NOT a part of the primary key

I have the following EF code-first entity and its corresponding configuration:

public class Category
{
public virtual long Id { get; set; }
public Guid Guid { get; set; }
public string Name { get; set; }
}

public class CategoryConfiguration:
EntityTypeConfiguration<Category>
{
public CategoryConfiguration ()
{
this.HasKey(entity => entity.Id);
this.Property(entity => entity.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.Property(entity => entity.Guid).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
}


Setting the
DatabaseGeneratedOption.Identity
option on the field
Guid
seems to have no effect and the corresponding table in SQL Server has the
IDENTITY
option disabled.

Is there a way to have a GUID/UNIQUEIDENTIFIER column in EF that is auto-generated but at the same time NOT part of the primary key?

Answer

EF doesn't "auto-generate" anything related to the ID, that's all handled by the database. Also DatabaseGeneratedOption.Identity isn't tied to the primary key, it's just an indicator to EF that the field value is generated by the DB and therefore should be pulled down.

As long as the default value in the database for your field is set to newid() or newsequentialid() then DatabaseGeneratedOption.Identity should work.