Search code examples
c#asp.net-mvc-4scaffoldingentity-framework-5

Cannot insert the value NULL even though column allows null


I'm testing out scaffolding with Entity Framework in Asp.Net MVC 4 (by following this article). I get it to work fine, except that even though my domain object allows null in a field and the database field allows null I get the error message:

Cannot insert the value NULL into column 'IsSuccessful', table 'MyTestProject.Persistence.TestContext.dbo.Prediction'; column does not allow nulls. UPDATE fails. The statement has been terminated.

My domain object looks like this:

public class Prediction 
{
    [Key]
    public int Id { get; set; }
    [Required]
    public string Title { get; set; }
    [Required]
    public string Description { get; set; }
    public bool? IsSuccessful { get; set; }
}

The generated web page shows IsSuccessful as a drop down box with the choices NotSet, True and False. In the database the column IsSuccessful allows null. Still I get the error message. Everything works fine if I choose True or False (it is saved correctly in the database), but not when I select NotSet.

Surely there must be a way around this?

Some details:

  • Visual Studio 2012 RC
  • Asp.Net MVC 4
  • EntityFramework.dll version 5.0.0.0

Solution

  • That error message looks like it is coming directly from SQL Server. If the server says the column is not nullable, then the column is not nullable. It knows best, after all.

    Treble check that the column is really nullable in the database. Also consider:

    • are you perhaps looking at a different database, with slightly different schema? i.e. one that has not had the correct DDL scripts applied (really easily done)
    • are you perhaps looking at a different object in the same database? In particular, are you perhaps looking at Halvard.Prediction, where-as the code is looking at dbo.Prediction ?