Raheel Khan Raheel Khan - 1 year ago 91
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:
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
option on the field
seems to have no effect and the corresponding table in SQL Server has the
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download