1

I have the following model entity:

public class ScheduledTask
    {
        public virtual int ScheduledTaskId { get; set; }    
        public virtual Incident TemplateIncident { get; set; }
        //Some props are omitted for simplicity    
        [Display(Name = "Next runtime")]
        [Required]
        [DataType(DataType.DateTime)]
        public virtual DateTime NextExecuteAfterDate { get; set; }
    }

It is a part of a DataContext as:

public DbSet<ScheduledTask> ScheduledTasks { get; set; }

A UI in a solution is an MVC3 site.

Whenever a user is saving a record, a schedulable task is being saved along:

_db.Add(new ScheduledTask
                        {
                            NextExecuteAfterDate = DateTime.MinValue,
                            Schedule = scheduleTypeId,
                            TemplateIncident = incident
                        });
            _db.SaveChanges();

As you can see, I am creating an instance of my entity class, assigning a DateTime property a minimum value and adding it to a DbContext. Then I call SaveChanges().

SaveChages() generates an

[SqlException (0x80131904): The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.]

A NextExecuteAfterDate in a database is a Column of a type datetime, not null.

Where does datetime2 come from, and how can I fix the problem and get EF to add a row to a table?

1 Answer 1

1

the sql server wants to store 1.1.0001 in the database, but thats not in the range of the SQL Server DateTimes. i haven't worked with EF that much but in other ORMs you can simply change the DateTime to Nullable and store a null value explicitly. like this:

public class ScheduledTask
{
    public virtual int ScheduledTaskId { get; set; }    
    public virtual Incident TemplateIncident { get; set; }
    //Some props are omitted for simplicity    
    [Display(Name = "Next runtime")]
    [DataType(DataType.DateTime)]
    public virtual DateTime? NextExecuteAfterDate { get; set; }
}

maybe this works with EF too

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, I wasn't aware of a fact, that .Net's DateTime.MinValue doesn't play along with SQLDateTime.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.