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:

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

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.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement