简体   繁体   中英

ASP.NET errors related to null and non-null values. Don't understand

I get this error when I 'update-database -Verbose' using Powershell:

The value of the complex property 'Address' on entity of type 'Student' is null. Complex properties cannot be set to null and values cannot be set for null complex properties.

or

{"Null value for non-nullable member. Member: 'Address'."}

This error also occurs when I try to create a new student or instructor. I think the problem is in the controller but that is 100's of line of code and I am not exactly sure where it is. Here is the code for Student.cs:

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")]
    [Range(typeof(double), "0.00", "1000.00")]
    public double? CreditsEarned { get; set; }

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

   public Address Address { get; set; }  // here is me using Address


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

Person class:

public abstract class Person
{
    public int ID { get; set; }

    // A Person 'has a' Address object 
    public Address Address { get; set; }

    [Required]
    [StringLength(50)]
    [Display(Name = "Last Name")]

    public string LastName { get; set; }
    [Required]
    [StringLength(50, ErrorMessage = "First name cannot be longer than 50 characters.")]
    [Column("FirstName")]
    [Display(Name = "First Name")]
}

And here is the Address class I created:

public class Address
{
    [Required]
    [RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")]
    public string Email { get; set; }

    [Required]
    [Compare("Email")]
    public string EmailConfirm { get; set; }
}

Your Person class is never creating an instance of Address so it is null . Add a constructor that creates an address to your Person class

public Person() 
{
    Address = new Address();
}

创建Student实例时,是否要初始化Address属性?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM