Skip to content
Advertisement

RawSQL and auto-generated keys in EF Core 3.1

I have a Model with a Guid primary key. I want the Database to generate a key on insert so I added the following annotations:

    public class Employee
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Guid employee_id { get; set; }

        [Required]
        public int employee_number { get; set; }

        //more props...
    }

Now I expected that inserts with RawSQL wouldn’t expect a primary key, however the folllowing statement doesn’t work when executred through ExecuteSqlRaw:

INSERT INTO employees (employee_number/**, more props*/) 
VALUES (123 /**,more props*/)

An error is caused by the DB about a non-nullable primary key. Explicitly inserting some random Guid works, but i figured the DB would take care of this.

Is the Identity annotation wrong?

Advertisement

Answer

You could miss one step.

When I add migration, ef core will generate a migration file. Then defaultValueSql: "newsequentialid()" need to be added here.

enter image description here

After excuting Update-Database, I can insert the record with RawSQL.

enter image description here

Edit:

Another method to use HasDefaultValueSql in DbContext.

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        
        modelBuilder.Entity<Employee>()
           .Property(b => b.employee_id)
           .HasDefaultValueSql("newsequentialid()");
    }
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement