Error saving field of type DateTime

4

I am setting up an example of Code First, but at the time of saving a field of type DateTime in the database I get the following error

  

Converting a datetime2 data type to a datetime data type   resulted in a value out of range. \ r \ nThe statement has been terminated.

     
em
 System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
 em
 System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.<Update>b__2(UpdateTranslator
 ut)    em
 System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T
 noChangesResult, Func\'2 updateFunction)    em
 System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update()  
 em
 System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__35()
 em
 System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func\'1
 func, IDbExecutionStrategy executionStrategy, Boolean
 startLocalTransaction, Boolean releaseConnectionOnSuccess)    em
 System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions
 options, IDbExecutionStrategy executionStrategy, Boolean
 startLocalTransaction)    em
 System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass2a.<SaveChangesInternal>b__27()
 em
 System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func'1
 operation)    em
 System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions
 options, Boolean executeInExistingTransaction)    em
 System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions
 options)    em
 System.Data.Entity.Internal.InternalContext.SaveChanges()

This happens as soon as I call ctx.SaveChanges(); .

using Modelo.Classes.Banco;
using Modelo.Classes.Contexto;
using System;
using System.Linq;

namespace AppConsoleTestes
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var ctx = new dbContexto())
            {
                var usuario = new Usuarios();

                usuario.nomeUsuario = "Marconcilio das Virgens";
                usuario.senha = "123456";
                usuario.senhaTemp = true;
                usuario.ativo = true;
                usuario.bloqueado = false;
                usuario.dtInclusao = DateTime.Now;
                usuario.dtAdmissao = DateTime.Now;
                usuario.dtInclusao = DateTime.Now;

                ctx.Usuarios.Add(usuario);
                ctx.SaveChanges();


                var teste = ctx.Usuarios.FirstOrDefault();
            }
        }
    }
}

My class in the template;

using System;
using System.ComponentModel.DataAnnotations;

namespace Modelo.Classes.Banco
{
    public class Usuarios
    {
        [Key]
        public Int32 idUsuario { get; set; }
        [Required, MaxLength(100)]
        public string nomeUsuario { get; set; }
        [MaxLength(2000)]
        public string obsUsuario { get; set; }
        [MaxLength(100)]
        public string email { get; set; }
        [MaxLength(100)]
        public string login { get; set; }
        [MaxLength(200)]
        public string senha { get; set; }
        [MaxLength(15)]
        public string telefone { get; set; }
        [MaxLength(15)]
        public string celular { get; set; }
        [MaxLength(14)]
        public string cpf { get; set; }
        [MaxLength(20)]
        public string nroMatricula { get; set; }
        public DateTime dtAdmissao { get; set; }
        public DateTime dtNascimento { get; set; }
        [Required]
        public bool senhaTemp { get; set; }
        [Required]
        public bool ativo { get; set; }
        [Required]
        public bool bloqueado { get; set; }
        public DateTime dtInclusao { get; set; }
        [Timestamp]
        public byte[] SeqAlteracao { get; set; }
    }
}

If I comment the fields of type DateTime and change the database with DbMigration and save command does not return the error.

I do not know if I'm doing something wrong or something is missing.

In the database types are being created with the correct type, the only thing I found strange was the line;

  

ALTER TABLE [dbo]. [Users] ADD DEFAULT ('1900-01-01T00: 00: 00,000')   FOR

for each field of type datetime

USE [ControleOrcamentario]
GO

/****** Object:  Table [dbo].[Usuarios]    Script Date: 23/11/2016 16:59:49 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Usuarios](
    [idUsuario] [int] IDENTITY(1,1) NOT NULL,
    [nomeUsuario] [nvarchar](100) NOT NULL,
    [obsUsuario] [nvarchar](2000) NULL,
    [email] [nvarchar](100) NULL,
    [login] [nvarchar](100) NULL,
    [senha] [nvarchar](200) NULL,
    [telefone] [nvarchar](15) NULL,
    [celular] [nvarchar](15) NULL,
    [cpf] [nvarchar](14) NULL,
    [nroMatricula] [nvarchar](20) NULL,
    [senhaTemp] [bit] NOT NULL,
    [ativo] [bit] NOT NULL,
    [bloqueado] [bit] NOT NULL,
    [dtAdmissao] [datetime] NOT NULL,
    [dtNascimento] [datetime] NOT NULL,
    [dtInclusao] [datetime] NOT NULL,
    [SeqAlteracao] [timestamp] NOT NULL,
 CONSTRAINT [PK_dbo.Usuarios] PRIMARY KEY CLUSTERED 
(
    [idUsuario] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[Usuarios] ADD  DEFAULT ('1900-01-01T00:00:00.000') FOR [dtAdmissao]
GO

ALTER TABLE [dbo].[Usuarios] ADD  DEFAULT ('1900-01-01T00:00:00.000') FOR [dtNascimento]
GO

ALTER TABLE [dbo].[Usuarios] ADD  DEFAULT ('1900-01-01T00:00:00.000') FOR [dtInclusao]
GO
    
asked by anonymous 23.11.2016 / 19:58

1 answer

3

I was able to resolve by declaring the type in OnModelCreating ();

This causes the table to not create the line;

ALTER TABLE [dbo].[Usuarios] ADD  DEFAULT ('1900-01-01T00:00:00.000') FOR [dtAdmissao]
GO

This value DEFAULT ('1900-01-01T00:00:00.000') , which was breaking my code.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Usuarios>()
       .Property(so => so.dtAdmissao)
       .HasColumnName("dtAdmissao")
       .HasColumnType("datetime");
    modelBuilder.Entity<Usuarios>()
      .Property(so => so.dtInclusao)
      .HasColumnName("dtInclusao")
      .HasColumnType("datetime");
    modelBuilder.Entity<Usuarios>()
      .Property(so => so.dtNascimento)
      .HasColumnName("dtNascimento")
      .HasColumnType("datetime");

    base.OnModelCreating(modelBuilder);
}
    
23.11.2016 / 21:03