16

我试图在我的下拉列表中允许空值,在我的数据库表中,我已经为 int 的特定字段设置了允许空值,但是当我运行代码时,我收到错误消息“可空对象必须有一个值”,我想问题可能出在 ModelState 中。

控制器

[HttpPost]
    public ActionResult Edit(Student student)
    {
        if (ModelState.IsValid)
        {
            db.Entry(student).State = EntityState.Modified;
            db.SaveChanges();
            Loan w = new Loan()
            {
                StudentID = student.StudentID,
                ISBN = student.ISBN.Value,
            };
            db.Loans.Add(w);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        ViewBag.ISBN1 = new SelectList(db.Books, "ISBN", "Titulli", student.ISBN);
        return View(student);
    }
4

3 回答 3

21

尝试获取没有价值的可空对象的值时,您会收到此错误。如果Loan.ISBN属性不可为空,那么您应该为该属性提供默认值

ISBN = student.ISBN.HasValue ? student.ISBN.Value : defaultValue
// or ISBN = student.ISBN ?? defaultValue
// or ISBN = student.ISBN.GetValueOrDefault()

如果Loan.ISBN属性是可空的,那么只需分配student.ISBN而不访问Value可空类型

ISBN = student.ISBN
于 2012-12-27T10:57:51.407 回答
6

使用合并运算符 ?? 执行相同任务的最短方法,如下所示:

ISBN = student.ISBN ?? defaultValue;

合并运算符的工作方式如下:如果第一个值(左侧)为空,则 C# 计算第二个表达式(右侧)。

于 2012-12-27T13:54:25.583 回答
5

当您尝试访问类型为 false的Value属性时,会发生此异常。请参阅MSDN 上的可空类型。所以首先检查这一行NullableHasValue

ISBN = student.ISBN.Value

看看是否ISBN不为空。您可能希望将此行更改为

ISBN = student.ISBN.GetValueOrDefault();
于 2012-12-27T11:09:06.187 回答