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:
x
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.
After excuting Update-Database
, I can insert the record with RawSQL.
Edit:
Another method to use HasDefaultValueSql
in DbContext.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Employee>()
.Property(b => b.employee_id)
.HasDefaultValueSql("newsequentialid()");
}