Getting this error:
System.Data.SqlClient.SqlException : The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range v
This follows on from stepanZ answer... I got this error when using Entity Framework Code First
with AutoMapper
.
When setting up the AutoMapping
we have createddt
, updateddt
, createdby
and updatedby
fields which are automatically set in our public override int SaveChanges()
function. When doing this you need to ensure you set these fields to be ignored by AutoMapper
, otherwise the database will get updated with null
for those fields when they are not supplied from the View
.
My issue was that I had put the source and destination around the wrong way, therefore trying to ignore the fields when setting the ViewModel
, instead of when setting the Model
.
The Mapping
looked like this when I recieved this error (note: the cfg.CreateMap
on the second line is mapping the Model
to the ViewModel
and setting the Ignore()
)
cfg.CreateMap();
cfg.CreateMap()
.ForMember(dest => dest.CreatedBy, opt => opt.Ignore())
.ForMember(dest => dest.CreatedDt, opt => opt.Ignore())
.ForMember(dest => dest.UpdatedBy, opt => opt.Ignore())
.ForMember(dest => dest.UpdatedDt, opt => opt.Ignore());
The source and destination should be ignored for a mapping from ViewModel
To Model
(note: The code below is correct where the Ignore()
is placed against the mapping for the ViewModel
to the Model
)
cfg.CreateMap();
cfg.CreateMap()
.ForMember(dest => dest.CreatedBy, opt => opt.Ignore())
.ForMember(dest => dest.CreatedDt, opt => opt.Ignore())
.ForMember(dest => dest.UpdatedBy, opt => opt.Ignore())
.ForMember(dest => dest.UpdatedDt, opt => opt.Ignore());