datetime2数据类型到datetime数据类型的转换导致超出范围的值。该语句已终止

时间:2018-12-24 20:53:50

标签: c# asp.net-mvc-5

我的模型中有以下代码

public int Id { get; set; }

    [Required]
    [StringLength(255)]
    public string Name { get; set; }

    public DateTime DateAdded { get; set; }

    [Display(Name = "Release Date")]
    public DateTime ReleaseDate { get; set; }

    [Display(Name = "Number in Stock")]
    public byte NumberInStock { get; set; }

    public Genre Genre { get; set; }

    [Display(Name = "Genre")]
    [Required]
    public byte GenreId { get; set; }

这是我的控制器编码器错误点显示

[HttpPost]
    public ActionResult Create(Movie movie)
    {
        _context.Movies.Add(movie);
        _context.SaveChanges();

        return RedirectToAction("Index", "Movies");
    }

这是视图

<div class="form-group">
    @Html.LabelFor(m => m.Movie.ReleaseDate)
    @Html.TextBoxFor(m => m.Movie.ReleaseDate, "{0:d MMM yyyy}", new { @class = "form-control" })
</div>
<div class="form-group">
    @Html.LabelFor(m => m.Movie.GenreId)
    @Html.DropDownListFor(m => m.Movie.GenreId, new SelectList(Model.Genres, "Id", "Name"), "Select Movie Genre", new { @class = "form-control" })
</div>
<div class="form-group">
    @Html.LabelFor(m => m.Movie.NumberInStock)
    @Html.TextBoxFor(m => m.Movie.NumberInStock, new { @class = "form-control" })
</div>

<button type="submit" class="btn btn-primary">Save</button>

单击提交按钮时,出现错误:

  

将datetime2数据类型转换为datetime数据类型会导致超出范围的值。

对这个问题有任何想法吗?我假设这是一个日期时间问题,但我无法解决问题。我是初学者。

1 个答案:

答案 0 :(得分:0)

日期时间列“ DateAdded”在sql中标记为不可为空

选项1(更改控制器):

[HttpPost]
public ActionResult Create(Movie movie)
{
    //setdate
    movie.DateAdded = Datetime.Now;
    _context.Movies.Add(movie);
    _context.SaveChanges();

    return RedirectToAction("Index", "Movies");
}

选项2(更改型号)

public class Movie 
{
    public int Id { get; set; }

    [Required]
    [StringLength(255)]
    public string Name { get; set; }

    public DateTime DateAdded { get; set; } = Datetime.Now;

    [Display(Name = "Release Date")]
    public DateTime ReleaseDate { get; set; }

    [Display(Name = "Number in Stock")]
    public byte NumberInStock { get; set; }

    public Genre Genre { get; set; }

    [Display(Name = "Genre")]
    [Required]
    public byte GenreId { get; set; }
}