How generated values work for Entity Framework Core (SQL Server)

.net-core entity-framework-core entity-framework-core-3.1 sql-server

Question

I am using EF Core 3.1 with SQL Server provider. If not specified otherwise EF Core uses generated values for entity keys. (The key is being generated by the provider, in this case SQL Server) In following documentation page I found statement that:

For example, when using SQL Server, values will be automatically generated for GUID properties (using the SQL Server sequential GUID algorithm)

I was using SQL Profiler to investigate EF core generated queries and I noticed that for adding an entity it generated following SQL:

exec sp_executesql N'SET NOCOUNT ON;
INSERT INTO [MySchema].[MyTable] ([Id],  ...)
VALUES (@p0, ...);
',N'@p0 uniqueidentifier, ...',@p0='B3DC06A3-2B58-46A0-9085-7A17B064433F', ... 

here I see that query already has GUID in the query, meaning that it obtains it before generating the query. But I have't noticed any attidional calls in SQL Profiler.

How does the generated values work behind the hood?

1
0
2/27/2020 1:09:47 PM

Popular Answer

So I misinterpreted the documentation. It doesn't actually use SQL Server to get the Guid value, but copied the algorithm itself and creates the Guid on server side. Which makes sense as you are saving a round trip.

You can find the algorithm here.

0
3/6/2020 7:51:36 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow