How to fix the datetime2 out-of-range conversion error using DbContext and SetInitializer?

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

Solution

You have to ensure that Start is greater than or equal to SqlDateTime.MinValue (January 1, 1753) - by default Start equals DateTime.MinValue (January 1, 0001).

Problem

I'm using the DbContext and Code First APIs introduced with Entity Framework 4.1. The data model uses basic data types such as `string` and `DateTime`. The only data annotation I'm using in some cases is `[Required]`, but that's not on any of the `DateTime` properties. Example: ``` public virtual DateTime Start { get; set; } ``` The DbContext subclass is also simple and looks like: ``` public class EventsContext : DbContext { public DbSet<Event> Events { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Event>().ToTable("Events"); } } ``` The initializer sets dates in the model to sensible values in either this year or next year. However when I run the initializer, I get this error at `context.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. I don't understand why this is happening at all because everything is so simple. I'm also not sure how to fix it since there is no edmx file to edit. Any ideas?

Original source

Related problems