For a database date field that holds the time the record was added, we typically set a default value of GETDATE() instead of getting the current time in the application's code to save it. This avoids the time skew caused by the Web server clock not synchronizing.
The Entity Framework Core is designed with this scenario in mind, provided . Hasdefaultvaluesql () mapping configuration, today in the actual development of a physical examination, it really works.
For example, the following database table dateadded and IsActive these 2 fields set the default values:
CREATE TABLE [dbo].[Log]( [Id] [int] IDENTITY(1,1) not NULL, [IP] [varchar]( -) not NULL, [dateadded] [datetime] not NULL DEFAULT(GETDATE()), [IsActive] [bit] not NULL DEFAULT((1)))
Use EF Core's hasdefaultvaluesql for mapping configuration:
Builder. Entity<log> (). Property (L = l.dateadded). Hasdefaultvaluesql (null); builder. Entity<Log> (). Property (L = l.isactive). Hasdefaultvaluesql (null);
The following SQL statement is generated when you save data in EF Core:
exec sp_executesql N'SET NOCOUNT on;insert into [Log] ([IP]) VALUES (@p0); SELECT [id], [dateadded], [Isactive]from [log]where @ @ROWCOUNT = 1 and [id] = scope_identity (); ', n'@p0 nvarchar',@p0=n'127.0.0.1 '
Ignores Hasdefaultvaluesql fields at insert, and assigns the default value SELECT to the property corresponding to the entity after insert.
The intimate Entity Framework core makes. NET core a lot more attractive.
Intimate with Entity Framework core: Gracefully handle database fields with default values