The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value

后端 未结 23 1404
旧时难觅i
旧时难觅i 2020-11-28 20:19

I have the following code in my HomeController:

public ActionResult Edit(int id)
{
    var ArticleToEdit = (from m in _db.ArticleSet where m.storyId == id se         


        
23条回答
  •  伪装坚强ぢ
    2020-11-28 21:03

    This one was driving me crazy. I wanted to avoid using a nullable date time (DateTime?). I didn't have the option of using SQL 2008's datetime2 type either (modelBuilder.Entity().Property(e => e.MyDateColumn).HasColumnType("datetime2");).

    I eventually opted for the following:

    public class MyDb : DbContext
    {
        public override int SaveChanges()
        {
            UpdateDates();
            return base.SaveChanges();
        }
    
        private void UpdateDates()
        {
            foreach (var change in ChangeTracker.Entries())
            {
                var values = change.CurrentValues;
                foreach (var name in values.PropertyNames)
                {
                    var value = values[name];
                    if (value is DateTime)
                    {
                        var date = (DateTime)value;
                        if (date < SqlDateTime.MinValue.Value)
                        {
                            values[name] = SqlDateTime.MinValue.Value;
                        }
                        else if (date > SqlDateTime.MaxValue.Value)
                        {
                            values[name] = SqlDateTime.MaxValue.Value;
                        }
                    }
                }
            }
        }
    }
    

提交回复
热议问题