How can I use DbContext and SetInitializer to correct the datetime2 out-of-range conversion error?

.net c# dbcontext ef-code-first entity-framework

Question

I'm using the Entity Framework 4.1-introduced DbContext and Code First APIs.

The Modeling data employs fundamental data types likestring and DateTime . In certain circumstances, the sole data annotation I use is[Required] although that is not included on any of theDateTime properties. Example:

public virtual DateTime Start { get; set; }

The Subclass of DbContext is also straightforward and resembles:

public class EventsContext : DbContext
{
    public DbSet<Event> Events { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Event>().ToTable("Events");
    }
}

Dates in the model are set to reasonable values in either current year or the next year by the initializer.

However, I see this problem when I execute the initializer atcontext.SaveChanges() :

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value. The statement has been terminated.

Everything is very basic, so I have no idea why this is occurring. Since there is no edmx file to change, I'm also unsure of how to solve it.

Any thoughts?

1
134
7/1/2017 7:17:37 PM

Accepted Answer

The Start value must be larger than or equal to the SqlDateTime value. By default, Start is equal to MinValue (January 1, 1743): DateTime. MinValue (January 1, 0001).

184
5/18/2011 9:12:11 PM

Popular Answer

Simple. Set the type of DateTime to DateTime? in your code first. Consequently, you may use the nullable DateTime type in databases. Example of an entity

public class Alarme
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }

        public DateTime? DataDisparado { get; set; }//.This allow you to work with nullable datetime in database.
        public DateTime? DataResolvido { get; set; }//.This allow you to work with nullable datetime in database.
        public long Latencia { get; set; }

        public bool Resolvido { get; set; }

        public int SensorId { get; set; }
        [ForeignKey("SensorId")]
        public virtual Sensor Sensor { get; set; }
    }


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow