Error saving Datetime type field

Asked

Viewed 3,123 times

4

I am mounting an example of Code First, but when saving a field of type Datetime in the database returns me the following error

Conversion of a datetime2 data type into a datetime data type resulted in a value outside the range. r the instruction has been completed.


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 I call it 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 model;

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 saved command does not return the error.

I don’t know if I’m doing something wrong or if something’s missing.

In the database the 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 datetime field

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
  • are the types of data in the database, are incompatible by the current configuration. In the database was created which type of datetime?

  • @Virgilionovic, I just edited with this, it seems that this generating correctly, I just found strange what it does with the DEFAULT declaration.

  • what is the bank? and version?

  • 1

    @Virgilionovic, Microsoft SQL Server 2012 - 11.0.2100.60 (Intel X86) Feb 10 2012 19:13:17 Copyright (c) Microsoft Corporation Express Edition on Windows NT 6.1 <X64> (Build 7601: Service Pack 1) (WOW64)

  • Try this: usuario.dtInclusao = DateTime.Now.Date

  • Try this also: http://answall.com/a/51034/54880

  • Have you tried to see if the problem isn’t in the field TimeStamp? This then occurs when you try to save null in a column of the type datetime which is NOT NULL.

  • @jbueno, I have already done a test without the columns of type datetime and saved nomalmente. resume is not the [Seqalteracao] [timestamp] NOT NULL field, which is causing the error.

  • Well I already had this problem when the Sqlserver was 2008 had this problem, but, it was in the field datetime

  • @Marconciliosouza You are sure that the date format of SQL Server is the same as the OS format (or defined in your application)?

  • @jbueno, this I don’t know

  • 1

    Well, then start there @Marconciliosouza

Show 7 more comments

2 answers

4


I managed to resolve declaring the type in Onmodelcreating();

This causes the table not to create the row;

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

That value DEFAULT ('1900-01-01T00:00:00.000') , who 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);
}
  • 2

    I was able to solve this by declaring an Annotations in the data field : [Column(Typename = "Datetime2")]

  • @Williamcézar, this create in the bank a field of type datime or Datetime2?

-2

Set in Annotations the dates that were set with the DEFAULT to fill in the Database

[Databasegenerated(Databasegeneratedoption.Computed)]

public Datetime dtAdmissao { get; set; }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.