C# 试图允许空值但......“可空对象必须有一个值”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14053519/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:33:25  来源:igfitidea点击:

Trying to allow nulls but... "Nullable object must have a value"

c#asp.net-mvcasp.net-mvc-4

提问by ilirvg

I am trying to allow nulls in my drop down list, in my database table I have set allow nulls for that specific field which is int, but when I run the code I get error saying "Nullable object must have a value", I think problem may be in ModelState.

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

Controller

控制器

[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);
    }

采纳答案by Sergey Berezovskiy

You are getting this error when trying to get value of nullableobject, which do not have value. If Loan.ISBNproperty is not nullable then you should provide default value for that property

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

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

If Loan.ISBNproperty is nullable, then simply assign student.ISBNwithout accessing Valueof nullable type

如果Loan.ISBN属性可以为空,则简单地赋值student.ISBN而不访问Value可空类型

ISBN = student.ISBN

回答by Zabavsky

This exception occurs when you try to access to the Valueproperty of Nullabletype when HasValueis false. See Nullable Typeson MSDN. So first of all check this line

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

ISBN = student.ISBN.Value

to see whether ISBNisn't null. You may want to change this line to

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

ISBN = student.ISBN.GetValueOrDefault();

回答by Reno

The shortest way to perform the same task, using the coalesce operator, ??, shown below:

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

ISBN = student.ISBN ?? defaultValue;

The coalesce operator works like this: if the first value (left hand side) is null, then C# evaluates the second expression (right hand side).

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