Entity Framework - Cannot insert the value NULL into column?

c# entity-framework-6 visual-studio

Question

I have looked at all the similar questions on this topic but none seem to work for me. I don't know exactly why I am getting the below error when I try to run these two commands: add-migration and then update-database.

Cannot insert the value NULL into column 'StudentId', table 'aspnet-JavaWebsiteProject-20171006053028.dbo.Groups'; column does not allow nulls. UPDATE fails. The statement has been terminated.

I am using Entity Framework v6.2.0. I have three simple models below:

public class Student
{
    public int Id { get; set; }

    public string UserId { get; set; }

    [EmailAddress]
    public string Email { get; set; }
}

Teacher model:

public class Teacher
{
        public int Id { get; set; }

        public string UserId { get; set; }

        [EmailAddress]
        public string Email { get; set; }
    }

//Group model:

public class Group
{
    public int Id { get; set; }

    [Required]
    public int StudentId { get; set; }
    public Student Student { get; set; }

    [Required]
    public int TeacherId { get; set; }
    public Teacher Teacher { get; set; }
} 

Can anyone guide me on what I might be doing wrong or how I can fix this error?

Thank you

1
0
2/16/2018 3:33:36 PM

Popular Answer

If you want the column to be nullable, you should set the property of your model to a nullable type.

public int? StudentId { get; set; }

After this, you will have to create and run your migrations again.

3
2/16/2018 3:36:11 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow