My SQL Server 2017 table is created in Transact-SQL as follows:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[JobTag]
(
[JobId] [int] NOT NULL,
[Name] [nvarchar](64) NOT NULL,
[Created] [datetime] NOT NULL,
[Value] [nvarchar](max) NULL,
[Comment] [nvarchar](2048) NULL,
CONSTRAINT [PK_JobTag_1]
PRIMARY KEY CLUSTERED ([JobId] ASC, [Name] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[JobTag]
ADD CONSTRAINT [DF_JobTag_Created] DEFAULT (GETDATE()) FOR [Created]
GO
ALTER TABLE [dbo].[JobTag] WITH CHECK
ADD CONSTRAINT [FK_JobTag_job]
FOREIGN KEY([JobId]) REFERENCES [dbo].[job] ([JobID])
GO
ALTER TABLE [dbo].[JobTag] CHECK CONSTRAINT [FK_JobTag_job]
GO
For the model I include
public System.DateTime Created { get; set; }
In .Net Core, when I try to add a record using
var newTag = new JobTag { JobId = job.JobID, Name = "myName", Value = myValueString};
connect.JobTags.Add(newTag)
connect.SaveChanges()
I get an error
Microsoft.EntityFrameworkCore.DbUpdateException:
An error occurred while updating the entries. See the inner exception for details.System.Data.SqlClient.SqlException: The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value
I do not get an error if I initialise the Created property with DateTime.Now.
If I remove the property from the model, then the SQL Server DateTime is used correctly.
Why do I need to initialize the property when it has a default value?
datetime2instead ofdatetimeforCreatedcolumndatetimeforCreatedcolumn during insert in database. You don't need to assign it manually in c# code.modelBuilder.Entity<Blog>().Property(b => b.Created).HasDefaultValueSql("getdate()");