Intimate with Entity Framework core: Gracefully handle database fields with default values

Source: Internet
Author: User
Tags getdate

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.