How do I resolve this error?
The 'CreditsEarned' property on 'Student' could not be set to a 'null' value. You must set this property to a non-null value of type 'System.Double'.
Here is my code:
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; }
}
May I ask you why do you want to set an double type to null ?
The double type in C# is not null by default. You must explicitly set it to null.
[Display(Name = "Credits Earned")]
public double? CreditsEarned { get; set; }
Notice the question mark after the declaration of the type. In C# this tells the compiler that that type might be flagged at nullable.
EDIT:
Please see following links:
Using Double?
(a ullable of type Double) instead, to allow the property to hold null-values has already been mentioned.
Another option may be to initialize the property to 0, and make sure it is always 0 or some other number.
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; }
you should try
// Credits earned
[Display(Name = "Credits Earned")]
public double? CreditsEarned { get; set; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.