简体   繁体   English

实体框架/ ASP.NET MVC 5 DateTime异常

[英]Entity Framework/ASP.NET MVC 5 DateTime Exception

I have Add and Edit actions in my MovieController that both go to the MovieForm View. 我在MovieController中添加和编辑动作都进入MovieForm视图。 Within the MovieForm view, I have the following: 在MovieForm视图中,我有以下内容:

@Html.TextBoxFor(m => m.Movie.ReleaseDate, "{0:MMM dd yyyy}", new { @class = "form-control" })

Also see my corresponding Movie model: 另见我相应的电影模型:

public class Movie
    {
        public int Id { get; set; }
        [Required]
        [StringLength(255)]
        public string Name { get; set; }

        public Genre Genre { get; set; }
        [Required]
        [Display(Name = "Genre")]
        public byte GenreId { get; set; }
        [Display(Name ="Release Date")]
        public DateTime ReleaseDate { get; set; }
        public DateTime DateAdded { get; set; }
        [Display(Name = "Number in Stock")]
        public int NumberInStock { get; set; }

    }

And ViewModel: 和ViewModel:

public class MovieFormViewModel
    {
        public IEnumerable<Genre> Genres { get; set; }
        public Movie Movie { get; set; }
        public bool IsNew { get; set; }
    }
}

So as you can see, there doesn't appear to be anything wrong with the ReleaseDate property. 正如您所看到的,ReleaseDate属性似乎没有任何问题。 In the database (localDB) it is of type "datetime". 在数据库(localDB)中,它的类型为“datetime”。

However, what's strange is that whenever I edit a movie and change the release date, everything is fine. 然而,奇怪的是,每当我编辑电影并更改发布日期时,一切都很好。 However, if I ADD a movie (even though its the same MovieForm), I get this Exception: 但是,如果我添加一部电影(即使它是同一个MovieForm),我会得到这个例外:

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value. 将datetime2数据类型转换为日期时间数据类型会导致超出范围的值。 The statement has been terminated. 该语句已终止。

I've tried stepping through it all and trying a try catch but that above error is the only thing I can extract out of what is going on. 我已经尝试逐步完成所有尝试捕获但是上面的错误是我唯一可以从正在发生的事情中提取的东西。 It just makes no sense to me that I can edit and successfully write to the database using the exact same form and exact same Save() action but for some reason, when it comes to creating a new entry, it's not working. 对我来说,使用完全相同的形式和完全相同的Save()动作编辑并成功写入数据库是没有意义的,但出于某种原因,当涉及到创建新条目时,它无法正常工作。 It'll even work if I enter the date exactly the same way directly into the DB. 如果我以完全相同的方式直接输入数据库,它甚至可以工作。

I've also seen this question however it is not addressing the issue that I'm having. 我也看过这个问题,但它没有解决我遇到的问题。 I'll even provide both my actions here so you can see them: 我甚至会在这里提供我的行动,以便您可以看到它们:

 public ActionResult Edit(int id)
        {
            var movie = _context.Movies.SingleOrDefault(m => m.Id == id);
            //Make sure that the id actually exists:
            if (movie == null)
            {
                return HttpNotFound();
            }
            var viewModel = new MovieFormViewModel
            {
                Movie = movie,
                IsNew = false,
                Genres = _context.Genres.ToList()
            };
            return View("MovieForm", viewModel);
        }

        public ActionResult Save(Movie movie)
        {
            if (movie.Id == 0)
            {
                _context.Movies.Add(movie);
            }
            else
            {
                //This method of data entry allows you to explicitly control which items in the Db can be updated by the user. More secured than an update-all method like TryUpdateModel()
                var movieInDb = _context.Movies.Single(c => c.Id == movie.Id);
                movieInDb.ReleaseDate = movie.ReleaseDate;
                movieInDb.Name = movie.Name;
                movieInDb.Genre = movie.Genre;
                movieInDb.NumberInStock = movie.NumberInStock;
                movieInDb.DateAdded = DateTime.Today.Date;
            }

                _context.SaveChanges();


            return RedirectToAction("Index", "Movies");
        }
public ActionResult New()
        {
            var genres = _context.Genres.ToList();
            var viewModel = new MovieFormViewModel
            {
                Genres = genres,
                IsNew = true
            };
            return View("MovieForm", viewModel);
        }

Note that the exception is occurring on the _context.SaveChanges() method. 请注意,_context.SaveChanges()方法发生异常。 Also note that I've tried removing the movieInDb.DateAdded = DateTime.Today.Date; 另请注意,我已尝试删除movieInDb.DateAdded = DateTime.Today.Date; but that doesn't have anything to do with it as I added it after I was experiencing this exception with the ReleaseDate. 但这与我没有任何关系,因为我在使用ReleaseDate遇到此异常后添加了它。 I also tried playing with the DateTime formatting of the ReleaseDate which didn't help either. 我也尝试使用ReleaseDate的DateTime格式,但这也没有用。

In the Save() Action in the MovieController, look carefully at the if statement. 在MovieController中的Save()Action中,仔细查看if语句。 Since the exception was happening only when a NEW movie was being added, this means that there was a problem in the case that movie.Id == 0 (new movie). 由于仅在添加新电影时发生异常,这意味着在movie.Id == 0(新电影)的情况下存在问题。 The problem was that the movie.DateAdded property was not being set by the form, thus it was never being set at all. 问题是movie.DateAdded属性没有被表单设置,因此它根本就没有被设置。 This was causing movie.DateAdded to be null and thus throwing the exception. 这导致movie.DateAdded为null,从而抛出异常。 The fix - set movie.DateAdded equal to the current date before the commit to the database like so: 修复 - 设置movie.DateAdded等于提交到数据库之前的当前日期如下所示:

if (movie.Id == 0)
            {
                movie.DateAdded = DateTime.Now;
                _context.Movies.Add(movie);
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM