将属性设置为类型为' System.Double'的非空值。

时间:2015-03-20 05:37:08

标签: c# asp.net

如何解决此错误?

  

' CreditsEarned'关于学生的财产'无法设置为' null'   值。您必须将此属性设置为类型的非null值   ' System.Double'

这是我的代码:

public class Student : Person
{
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    [Display(Name = "Enrollment Date")]
    public DateTime EnrollmentDate { get; set; }

    // Credits earned
    [Display(Name = "Credits Earned")]
    public double CreditsEarned { get; set; }

    // GPA
    [Display(Name = "GPA")]
    [Range(typeof(double), "0.7", "4.0")]
    public double Gpa { get; set; }


    public virtual ICollection<Enrollment> Enrollments { get; set; }
}

3 个答案:

答案 0 :(得分:1)

我可以问你为什么要将double类型设置为null?

默认情况下,C#中的double类型不为null。您必须将其明确设置为null。

[Display(Name = "Credits Earned")]
public double? CreditsEarned { get; set; }

在声明类型后注意问号。在C#中,这告诉编译器该类型可能被标记为可为空。

编辑:

请参阅以下链接:

1)Nullable Types in C#

2)Nullable Types in C# examples

答案 1 :(得分:0)

已经提到使用Double?(类型为Double的ullable)来允许属性保存空值。

另一个选项可能是将属性初始化为0,并确保它始终为0或其他数字。

public class Student : Person
{
    // This will make sure the value is initially defined (to 0):
    public Student(){
        CreditsEarned = 0;
    }

    ...

    // Credits earned
    [Display(Name = "Credits Earned")]
    public double CreditsEarned { get; set; }

答案 2 :(得分:-1)

你应该试试

// Credits earned
[Display(Name = "Credits Earned")]
public double? CreditsEarned { get; set; }