'datetime2' error when using entity framework in VS 2010 .net 4.0

前端 未结 16 1245
半阙折子戏
半阙折子戏 2020-11-29 00:04

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

16条回答
  •  一生所求
    2020-11-29 00:43

    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());
    

提交回复
热议问题